boon-deadlock 0.1.0

Boon is a Deadlock demo / replay file parser
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
use std::path::Path;

use memmap2::Mmap;
use prost::Message;

use crate::entity::{
    ClassInfo, EntityContainer, FieldDecodeContext, SerializerContainer, StringTableContainer,
};
use crate::error::{Error, Result};
use crate::io::{BitReader, ByteReader};

use std::collections::HashMap;

use super::command::{self, CmdHeader, dem, ge, svc};

use boon_proto::proto::{
    CDemoClassInfo, CDemoFileHeader, CDemoFileInfo, CDemoFullPacket, CDemoPacket, CDemoSendTables,
    CMsgSource1LegacyGameEvent, CMsgSource1LegacyGameEventList, CitadelUserMessageIds,
    CsvcMsgCreateStringTable, CsvcMsgPacketEntities, CsvcMsgServerInfo, CsvcMsgUpdateStringTable,
    CsvcMsgUserMessage, EBaseUserMessages, ECitadelGameEvents,
};

/// Magic bytes at the start of every Source 2 demo file.
const MAGIC: &[u8; 8] = b"PBDEMS2\0";
/// File header: 8 bytes magic + 4 bytes fileinfo_offset + 4 bytes spawngroups_offset.
const HEADER_SIZE: usize = 16;

/// Default tick rate (1/30 s). Used to compute `full_packet_interval` when
/// `CSVCMsg_ServerInfo.tick_interval` is not yet available.
const DEFAULT_TICK_INTERVAL: f32 = 1.0 / 30.0;
/// Default number of ticks between full-packet snapshots (at 30 Hz).
const DEFAULT_FULL_PACKET_INTERVAL: i32 = 1800;

/// Scratch buffer size for decompressed command bodies and packet payloads.
const BUF_SIZE: usize = 2 * 1024 * 1024;

/// Information about a demo message in the command stream.
#[derive(Debug, Clone, serde::Serialize)]
pub struct MessageInfo {
    /// Zero-based ordinal position in the command stream.
    pub index: usize,
    /// Command type (one of the `dem::*` constants).
    pub cmd: i32,
    /// Human-readable command name.
    pub cmd_name: String,
    /// Game tick this command applies to.
    pub tick: i32,
    /// Whether the body is Snappy-compressed.
    pub compressed: bool,
    /// Body size in bytes (before decompression).
    pub body_size: u32,
    /// Absolute byte offset from the start of the file.
    pub offset: usize,
}

/// Full parser context after initialization.
///
/// Holds all decoded game state: serializers, class definitions, string
/// tables, and live entities. Returned by [`Parser::parse_init`],
/// [`Parser::parse_to_tick`], and updated incrementally during
/// [`Parser::run_to_end`].
pub struct Context {
    /// Field definitions for every entity class.
    pub serializers: SerializerContainer,
    /// Maps numeric class IDs to network names.
    pub class_info: ClassInfo,
    /// Key-value tables (models, sounds, instance baselines, etc.).
    pub string_tables: StringTableContainer,
    /// Currently active entities keyed by entity index.
    pub entities: EntityContainer,
    /// Seconds per tick (from `CSVCMsg_ServerInfo`).
    pub tick_interval: f32,
    /// Ticks between full-packet snapshots (derived from tick_interval).
    pub full_packet_interval: i32,
    /// Most recent tick processed.
    pub tick: i32,
}

/// A game event extracted from the demo.
#[derive(Debug, Clone, serde::Serialize)]
pub struct GameEvent {
    /// Game tick at which this event occurred.
    pub tick: i32,
    /// Human-readable event name (e.g. `"player_death"`, `"k_ECitadelUserMsg_Damage"`).
    pub name: String,
    /// Numeric message type from the packet stream.
    pub msg_type: u32,
    /// Key-value pairs for Source 1 legacy game events; empty for user messages.
    pub keys: Vec<(String, String)>,
    /// Raw protobuf bytes of the event. Use [`crate::decode_event_payload`] to decode.
    #[serde(skip)]
    pub payload: Vec<u8>,
}

struct EventDescriptor {
    name: String,
    field_names: Vec<String>,
}

fn format_event_key(key: &boon_proto::proto::c_msg_source1_legacy_game_event::KeyT) -> String {
    if let Some(ref s) = key.val_string {
        return s.clone();
    }
    if let Some(f) = key.val_float {
        return f.to_string();
    }
    if let Some(l) = key.val_long {
        return l.to_string();
    }
    if let Some(s) = key.val_short {
        return s.to_string();
    }
    if let Some(b) = key.val_byte {
        return b.to_string();
    }
    if let Some(b) = key.val_bool {
        return b.to_string();
    }
    if let Some(u) = key.val_uint64 {
        return u.to_string();
    }
    String::new()
}

/// Internal storage for demo data — either memory-mapped or an owned byte buffer.
enum Storage {
    Mmap(Mmap),
    Bytes(Vec<u8>),
}

impl AsRef<[u8]> for Storage {
    fn as_ref(&self) -> &[u8] {
        match self {
            Storage::Mmap(m) => m,
            Storage::Bytes(b) => b,
        }
    }
}

/// The main parser. Owns the demo file data (memory-mapped or in-memory).
pub struct Parser {
    storage: Storage,
}

impl Parser {
    /// Open a demo file and memory-map it for zero-copy parsing.
    pub fn from_file(path: &Path) -> Result<Self> {
        let file = std::fs::File::open(path)?;
        // SAFETY: The file is opened read-only and the mapping lives as
        // long as the Parser.  Undefined behavior can occur if an external
        // process truncates or modifies the file while mapped; callers must
        // ensure the file is not concurrently mutated.
        let mmap = unsafe { Mmap::map(&file)? };
        Ok(Self {
            storage: Storage::Mmap(mmap),
        })
    }

    /// Create a parser from an in-memory byte buffer.
    ///
    /// This is useful for testing, WASM targets (where mmap is unavailable),
    /// or when the demo data has already been loaded into memory.
    pub fn from_bytes(bytes: Vec<u8>) -> Self {
        Self {
            storage: Storage::Bytes(bytes),
        }
    }

    /// Returns the raw demo data.
    fn data(&self) -> &[u8] {
        self.storage.as_ref()
    }

    /// Verify magic bytes.
    /// Verify that the file has valid demo magic bytes.
    pub fn verify(&self) -> Result<()> {
        if self.data().len() < HEADER_SIZE {
            return Err(Error::Parse {
                context: "file too small for demo header".into(),
            });
        }

        let mut magic = [0u8; 8];
        magic.copy_from_slice(&self.data()[0..8]);
        if &magic != MAGIC {
            return Err(Error::InvalidMagic { got: magic });
        }

        Ok(())
    }

    fn read_cmd_header(reader: &mut ByteReader) -> Result<CmdHeader> {
        let raw_cmd = reader.read_uvarint32()?;
        let compress_flag = dem::IS_COMPRESSED;
        let compressed = (raw_cmd & compress_flag) != 0;
        let cmd = (raw_cmd & !compress_flag) as i32;
        let tick_raw = reader.read_uvarint32()?;
        let tick = tick_raw as i32;
        let body_size = reader.read_uvarint32()?;
        Ok(CmdHeader {
            cmd,
            tick,
            compressed,
            body_size,
        })
    }

    /// Read and decompress a command body into the provided buffer.
    /// The buffer is resized as needed and can be reused across calls.
    fn read_cmd_body(reader: &mut ByteReader, header: &CmdHeader, buf: &mut Vec<u8>) -> Result<()> {
        let raw = reader.read_bytes(header.body_size as usize)?;
        if header.compressed {
            let decompressed_len =
                snap::raw::decompress_len(raw).map_err(|e| Error::Decompress(e.to_string()))?;
            buf.clear();
            buf.resize(decompressed_len, 0);
            snap::raw::Decoder::new()
                .decompress(raw, buf)
                .map_err(|e| Error::Decompress(e.to_string()))?;
        } else {
            buf.clear();
            buf.extend_from_slice(raw);
        }
        Ok(())
    }

    /// Iterate all commands and return metadata about each.
    /// Continues past DEM_Stop to capture DEM_FileInfo.
    pub fn messages(&self) -> Result<Vec<MessageInfo>> {
        self.verify()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);
        let mut messages = Vec::new();
        let mut index = 0;

        while reader.remaining() > 0 {
            let offset = reader.position() + HEADER_SIZE;
            let header = match Self::read_cmd_header(&mut reader) {
                Ok(h) => h,
                Err(_) => break,
            };

            messages.push(MessageInfo {
                index,
                cmd: header.cmd,
                cmd_name: command::command_name(header.cmd).to_string(),
                tick: header.tick,
                compressed: header.compressed,
                body_size: header.body_size,
                offset,
            });

            // DEM_Stop has no body, and DEM_FileInfo follows it
            if header.cmd == dem::STOP {
                index += 1;
                continue;
            }

            // DEM_FileInfo comes after DEM_Stop; once we've read it, we're done
            if header.cmd == dem::FILE_INFO {
                reader.skip(header.body_size as usize).ok();
                break;
            }

            if reader.skip(header.body_size as usize).is_err() {
                break;
            }

            index += 1;
        }

        Ok(messages)
    }

    /// Find and decode the CDemoFileHeader message.
    pub fn file_header(&self) -> Result<CDemoFileHeader> {
        self.verify()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);
        let mut body_buf = Vec::with_capacity(BUF_SIZE);

        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;

            if header.cmd == dem::FILE_HEADER {
                Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;
                return CDemoFileHeader::decode(&body_buf[..]).map_err(Error::from);
            }

            if header.cmd == dem::STOP {
                break;
            }

            reader.skip(header.body_size as usize)?;
        }

        Err(Error::Parse {
            context: "DEM_FileHeader not found".into(),
        })
    }

    /// Decode CDemoFileInfo using the offset stored in the file header.
    pub fn file_info(&self) -> Result<CDemoFileInfo> {
        self.verify()?;

        // Bytes 8..12 of the file header contain the absolute offset to DEM_FileInfo.
        let fileinfo_offset = u32::from_le_bytes([
            self.data()[8],
            self.data()[9],
            self.data()[10],
            self.data()[11],
        ]) as usize;

        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);
        // The offset is relative to the start of the file; adjust for the header we sliced off.
        reader.seek(fileinfo_offset.saturating_sub(HEADER_SIZE))?;

        let header = Self::read_cmd_header(&mut reader)?;
        if header.cmd != dem::FILE_INFO {
            return Err(Error::Parse {
                context: format!(
                    "expected DEM_FileInfo at offset {}, found command {}",
                    fileinfo_offset, header.cmd
                ),
            });
        }

        let mut body_buf = Vec::new();
        Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;
        CDemoFileInfo::decode(&body_buf[..]).map_err(Error::from)
    }

    /// Parse game events from the demo.
    ///
    /// Extracts Source 1 legacy game events and Citadel user messages from
    /// `DEM_Packet`, `DEM_SignonPacket`, and `DEM_FullPacket` commands.
    /// If `max_tick` is set, stops parsing once the tick exceeds the limit.
    pub fn events(&self, max_tick: Option<i32>) -> Result<Vec<GameEvent>> {
        self.verify()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);
        let mut body_buf = Vec::with_capacity(BUF_SIZE);
        let mut packet_buf = vec![0u8; BUF_SIZE];
        let mut events = Vec::new();
        let mut descriptors: HashMap<i32, EventDescriptor> = HashMap::new();

        while reader.remaining() > 0 {
            let header = match Self::read_cmd_header(&mut reader) {
                Ok(h) => h,
                Err(_) => break,
            };

            if header.cmd == dem::STOP {
                break;
            }

            if let Some(max) = max_tick
                && header.tick > max
            {
                break;
            }

            match header.cmd {
                dem::PACKET | dem::SIGNON_PACKET => {
                    Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;
                    let cmd = CDemoPacket::decode(&body_buf[..])?;
                    let pkt_data = cmd.data.unwrap_or_default();
                    Self::process_packet_events(
                        &pkt_data,
                        header.tick,
                        &mut descriptors,
                        &mut events,
                        &mut packet_buf,
                    )?;
                }
                dem::FULL_PACKET => {
                    Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;
                    let cmd = CDemoFullPacket::decode(&body_buf[..])?;
                    if let Some(packet) = cmd.packet {
                        let pkt_data = packet.data.unwrap_or_default();
                        Self::process_packet_events(
                            &pkt_data,
                            header.tick,
                            &mut descriptors,
                            &mut events,
                            &mut packet_buf,
                        )?;
                    }
                }
                _ => {
                    reader.skip(header.body_size as usize)?;
                }
            }
        }

        Ok(events)
    }

    /// Process a packet's inner messages for game events.
    fn process_packet_events(
        pkt_data: &[u8],
        tick: i32,
        descriptors: &mut HashMap<i32, EventDescriptor>,
        events: &mut Vec<GameEvent>,
        packet_buf: &mut Vec<u8>,
    ) -> Result<()> {
        let mut br = BitReader::new(pkt_data);

        while br.bits_remaining() > 8 {
            let msg_type = br.read_ubitvar()?;
            let size = br.read_uvarint32()? as usize;

            if size > packet_buf.len() {
                packet_buf.resize(size, 0);
            }
            br.read_bytes(&mut packet_buf[..size])?;
            let msg_data = &packet_buf[..size];

            match msg_type {
                ge::SOURCE1_LEGACY_GAME_EVENT_LIST => {
                    let msg = CMsgSource1LegacyGameEventList::decode(msg_data)?;
                    for desc in msg.descriptors {
                        let eventid = desc.eventid.unwrap_or_default();
                        let name = desc.name.unwrap_or_default();
                        let field_names = desc
                            .keys
                            .iter()
                            .map(|k| k.name.clone().unwrap_or_default())
                            .collect();
                        descriptors.insert(eventid, EventDescriptor { name, field_names });
                    }
                }
                ge::SOURCE1_LEGACY_GAME_EVENT => {
                    let msg = CMsgSource1LegacyGameEvent::decode(msg_data)?;
                    let eventid = msg.eventid.unwrap_or_default();
                    let (name, keys) = if let Some(desc) = descriptors.get(&eventid) {
                        let keys: Vec<(String, String)> = desc
                            .field_names
                            .iter()
                            .zip(msg.keys.iter())
                            .map(|(fname, key)| (fname.clone(), format_event_key(key)))
                            .collect();
                        (desc.name.clone(), keys)
                    } else {
                        let name = msg
                            .event_name
                            .unwrap_or_else(|| format!("event_{}", eventid));
                        (name, Vec::new())
                    };
                    events.push(GameEvent {
                        tick,
                        name,
                        msg_type,
                        keys,
                        payload: msg_data.to_vec(),
                    });
                }
                svc::USER_MESSAGE => {
                    let msg = CsvcMsgUserMessage::decode(msg_data)?;
                    let inner_type = msg.msg_type.unwrap_or_default();
                    let name = command::user_message_name(inner_type);
                    let inner_payload = msg.msg_data.unwrap_or_default();
                    events.push(GameEvent {
                        tick,
                        name,
                        msg_type: inner_type as u32,
                        keys: Vec::new(),
                        payload: inner_payload,
                    });
                }
                _ => {
                    // Citadel user messages (300-366) are sent directly in
                    // the packet stream, not wrapped in CSVCMsg_UserMessage.
                    let t = msg_type as i32;
                    let name = if let Ok(e) = CitadelUserMessageIds::try_from(t) {
                        Some(e.as_str_name().to_string())
                    } else if let Ok(e) = ECitadelGameEvents::try_from(t) {
                        Some(e.as_str_name().to_string())
                    } else if let Ok(e) = EBaseUserMessages::try_from(t) {
                        Some(e.as_str_name().to_string())
                    } else {
                        None
                    };
                    if let Some(name) = name {
                        events.push(GameEvent {
                            tick,
                            name,
                            msg_type,
                            keys: Vec::new(),
                            payload: msg_data.to_vec(),
                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Parse send tables from DEM_SendTables command.
    pub fn parse_send_tables(&self) -> Result<SerializerContainer> {
        self.verify()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);
        let mut body_buf = Vec::with_capacity(BUF_SIZE);

        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;

            if header.cmd == dem::SEND_TABLES {
                Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;
                let cmd = CDemoSendTables::decode(&body_buf[..])?;
                return SerializerContainer::parse(cmd);
            }

            if header.cmd == dem::STOP || header.cmd == dem::SYNC_TICK {
                break;
            }

            reader.skip(header.body_size as usize)?;
        }

        Err(Error::Parse {
            context: "DEM_SendTables not found".into(),
        })
    }

    /// Parse class info from DEM_ClassInfo command.
    pub fn parse_class_info(&self) -> Result<ClassInfo> {
        self.verify()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);
        let mut body_buf = Vec::with_capacity(BUF_SIZE);

        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;

            if header.cmd == dem::CLASS_INFO {
                Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;
                let cmd = CDemoClassInfo::decode(&body_buf[..])?;
                return Ok(ClassInfo::parse(cmd));
            }

            if header.cmd == dem::STOP || header.cmd == dem::SYNC_TICK {
                break;
            }

            reader.skip(header.body_size as usize)?;
        }

        Err(Error::Parse {
            context: "DEM_ClassInfo not found".into(),
        })
    }

    /// Parse all initialization data up to DEM_SyncTick and return a Context.
    pub fn parse_init(&self) -> Result<Context> {
        self.verify()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);

        let mut packet_buf = vec![0u8; BUF_SIZE];
        let mut body_buf = Vec::with_capacity(BUF_SIZE);

        let mut serializers: Option<SerializerContainer> = None;
        let mut class_info: Option<ClassInfo> = None;
        let mut string_tables = StringTableContainer::new();
        let mut tick_interval: f32 = 0.0;
        let mut full_packet_interval: i32 = DEFAULT_FULL_PACKET_INTERVAL;

        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;

            if header.cmd == dem::SYNC_TICK {
                reader.skip(header.body_size as usize)?;
                break;
            }

            if header.cmd == dem::STOP {
                break;
            }

            Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;

            match header.cmd {
                dem::SEND_TABLES => {
                    let cmd = CDemoSendTables::decode(&body_buf[..])?;
                    serializers = Some(SerializerContainer::parse(cmd)?);
                }
                dem::CLASS_INFO => {
                    let cmd = CDemoClassInfo::decode(&body_buf[..])?;
                    class_info = Some(ClassInfo::parse(cmd));
                }
                dem::PACKET | dem::SIGNON_PACKET => {
                    let cmd = CDemoPacket::decode(&body_buf[..])?;
                    let pkt_data = cmd.data.unwrap_or_default();
                    Self::process_packet_for_init(
                        &pkt_data,
                        &mut string_tables,
                        &mut tick_interval,
                        &mut full_packet_interval,
                        &mut packet_buf,
                    )?;
                }
                _ => {}
            }
        }

        let serializers = serializers.ok_or_else(|| Error::Parse {
            context: "DEM_SendTables not found during init".into(),
        })?;
        let class_info = class_info.ok_or_else(|| Error::Parse {
            context: "DEM_ClassInfo not found during init".into(),
        })?;

        // Update instance baselines
        string_tables.update_instance_baselines(&class_info);

        Ok(Context {
            serializers,
            class_info,
            string_tables,
            entities: EntityContainer::new(),
            tick_interval,
            full_packet_interval,
            tick: -1,
        })
    }

    /// Process a packet's inner messages during initialization (string tables, server info).
    fn process_packet_for_init(
        pkt_data: &[u8],
        string_tables: &mut StringTableContainer,
        tick_interval: &mut f32,
        full_packet_interval: &mut i32,
        packet_buf: &mut Vec<u8>,
    ) -> Result<()> {
        let mut br = BitReader::new(pkt_data);

        while br.bits_remaining() > 8 {
            let msg_type = br.read_ubitvar()?;
            let size = br.read_uvarint32()? as usize;

            // Read the message body
            if size > packet_buf.len() {
                packet_buf.resize(size, 0);
            }
            br.read_bytes(&mut packet_buf[..size])?;
            let msg_data = &packet_buf[..size];

            match msg_type {
                svc::CREATE_STRING_TABLE => {
                    let msg = CsvcMsgCreateStringTable::decode(msg_data)?;
                    string_tables.handle_create(msg)?;
                }
                svc::UPDATE_STRING_TABLE => {
                    let msg = CsvcMsgUpdateStringTable::decode(msg_data)?;
                    string_tables.handle_update(msg)?;
                }
                svc::SERVER_INFO => {
                    let msg = CsvcMsgServerInfo::decode(msg_data)?;
                    if let Some(ti) = msg.tick_interval {
                        *tick_interval = ti;
                        let ratio = DEFAULT_TICK_INTERVAL / ti;
                        *full_packet_interval = DEFAULT_FULL_PACKET_INTERVAL * ratio as i32;
                    }
                }
                _ => {}
            }
        }

        Ok(())
    }

    /// Parse the demo to a specific tick, returning the full game state.
    ///
    /// Uses an optimisation where it skips forward to the last
    /// `DEM_FullPacket` snapshot before `target_tick`, applies that snapshot,
    /// then replays individual packets until `target_tick` is reached.
    pub fn parse_to_tick(&self, target_tick: i32) -> Result<Context> {
        let mut ctx = self.parse_init()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);

        let mut packet_buf = vec![0u8; BUF_SIZE];
        let mut body_buf = Vec::with_capacity(BUF_SIZE);
        let mut fp_buf = Vec::with_capacity(256);
        let mut field_decode_ctx = FieldDecodeContext::new(ctx.tick_interval);

        // Skip past init (up to and including SyncTick)
        let mut past_sync = false;
        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;
            if header.cmd == dem::SYNC_TICK {
                reader.skip(header.body_size as usize)?;
                past_sync = true;
                break;
            }
            if header.cmd == dem::STOP {
                return Ok(ctx);
            }
            reader.skip(header.body_size as usize)?;
        }

        if !past_sync {
            return Ok(ctx);
        }

        // Track whether we've handled the last full packet before target
        let mut did_handle_last_full_packet = false;

        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;

            if header.tick > target_tick && header.cmd != dem::STOP {
                break;
            }

            ctx.tick = header.tick;

            if header.cmd == dem::STOP {
                break;
            }

            let is_full_packet = header.cmd == dem::FULL_PACKET;
            let distance = target_tick - header.tick;
            let has_full_packet_ahead = distance > ctx.full_packet_interval + 100;

            if is_full_packet {
                Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;
                let cmd = CDemoFullPacket::decode(&body_buf[..])?;

                // Handle string tables from full packet
                if let Some(st) = cmd.string_table {
                    ctx.string_tables.do_full_update(st);
                    ctx.string_tables.update_instance_baselines(&ctx.class_info);
                }

                // Handle packet from full packet (skip if more full packets ahead)
                if !has_full_packet_ahead {
                    if let Some(packet) = cmd.packet {
                        let pkt_data = packet.data.unwrap_or_default();
                        Self::process_packet_entities(
                            &pkt_data,
                            &mut ctx,
                            &mut field_decode_ctx,
                            &mut packet_buf,
                            &mut fp_buf,
                        )?;
                    }
                    did_handle_last_full_packet = true;
                }

                continue;
            }

            if !did_handle_last_full_packet {
                reader.skip(header.body_size as usize)?;
                continue;
            }

            Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;

            match header.cmd {
                dem::PACKET | dem::SIGNON_PACKET => {
                    let cmd = CDemoPacket::decode(&body_buf[..])?;
                    let pkt_data = cmd.data.unwrap_or_default();
                    Self::process_packet_entities(
                        &pkt_data,
                        &mut ctx,
                        &mut field_decode_ctx,
                        &mut packet_buf,
                        &mut fp_buf,
                    )?;
                }
                _ => {}
            }
        }

        Ok(ctx)
    }

    /// Parse the entire demo, calling a callback at each tick with the current context.
    /// This is more efficient than calling parse_to_tick repeatedly.
    pub fn run_to_end<F>(&self, mut on_tick: F) -> Result<()>
    where
        F: FnMut(&Context),
    {
        let mut ctx = self.parse_init()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);

        let mut packet_buf = vec![0u8; BUF_SIZE];
        let mut body_buf = Vec::with_capacity(BUF_SIZE);
        let mut fp_buf = Vec::with_capacity(256);
        let mut field_decode_ctx = FieldDecodeContext::new(ctx.tick_interval);

        // Skip past init (up to and including SyncTick)
        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;
            if header.cmd == dem::SYNC_TICK {
                reader.skip(header.body_size as usize)?;
                break;
            }
            if header.cmd == dem::STOP {
                return Ok(());
            }
            reader.skip(header.body_size as usize)?;
        }

        let mut last_tick: i32 = -1;

        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;

            // Call callback when tick changes
            if header.tick != last_tick && last_tick >= 0 {
                on_tick(&ctx);
            }
            last_tick = header.tick;
            ctx.tick = header.tick;

            if header.cmd == dem::STOP {
                // Final callback
                if last_tick >= 0 {
                    on_tick(&ctx);
                }
                break;
            }

            Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;

            match header.cmd {
                dem::FULL_PACKET => {
                    let cmd = CDemoFullPacket::decode(&body_buf[..])?;

                    if let Some(st) = cmd.string_table {
                        ctx.string_tables.do_full_update(st);
                        ctx.string_tables.update_instance_baselines(&ctx.class_info);
                    }

                    if let Some(packet) = cmd.packet {
                        let pkt_data = packet.data.unwrap_or_default();
                        Self::process_packet_entities(
                            &pkt_data,
                            &mut ctx,
                            &mut field_decode_ctx,
                            &mut packet_buf,
                            &mut fp_buf,
                        )?;
                    }
                }
                dem::PACKET | dem::SIGNON_PACKET => {
                    let cmd = CDemoPacket::decode(&body_buf[..])?;
                    let pkt_data = cmd.data.unwrap_or_default();
                    Self::process_packet_entities(
                        &pkt_data,
                        &mut ctx,
                        &mut field_decode_ctx,
                        &mut packet_buf,
                        &mut fp_buf,
                    )?;
                }
                _ => {}
            }
        }

        Ok(())
    }

    /// Parse the entire demo with entity class filtering.
    /// Only entities with classes in the filter are fully tracked.
    /// This is much faster when you only need specific entity types.
    pub fn run_to_end_filtered<F>(
        &self,
        class_filter: &std::collections::HashSet<&str>,
        mut on_tick: F,
    ) -> Result<()>
    where
        F: FnMut(&Context),
    {
        let mut ctx = self.parse_init()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);

        let mut packet_buf = vec![0u8; BUF_SIZE];
        let mut body_buf = Vec::with_capacity(BUF_SIZE);
        let mut fp_buf = Vec::with_capacity(256);
        let mut field_decode_ctx = FieldDecodeContext::new(ctx.tick_interval);

        // Skip past init (up to and including SyncTick)
        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;
            if header.cmd == dem::SYNC_TICK {
                reader.skip(header.body_size as usize)?;
                break;
            }
            if header.cmd == dem::STOP {
                return Ok(());
            }
            reader.skip(header.body_size as usize)?;
        }

        let mut last_tick: i32 = -1;

        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;

            // Call callback when tick changes
            if header.tick != last_tick && last_tick >= 0 {
                on_tick(&ctx);
            }
            last_tick = header.tick;
            ctx.tick = header.tick;

            if header.cmd == dem::STOP {
                // Final callback
                if last_tick >= 0 {
                    on_tick(&ctx);
                }
                break;
            }

            Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;

            match header.cmd {
                dem::FULL_PACKET => {
                    let cmd = CDemoFullPacket::decode(&body_buf[..])?;

                    if let Some(st) = cmd.string_table {
                        ctx.string_tables.do_full_update(st);
                        ctx.string_tables.update_instance_baselines(&ctx.class_info);
                    }

                    if let Some(packet) = cmd.packet {
                        let pkt_data = packet.data.unwrap_or_default();
                        Self::process_packet_entities_filtered(
                            &pkt_data,
                            &mut ctx,
                            &mut field_decode_ctx,
                            &mut packet_buf,
                            class_filter,
                            &mut fp_buf,
                        )?;
                    }
                }
                dem::PACKET | dem::SIGNON_PACKET => {
                    let cmd = CDemoPacket::decode(&body_buf[..])?;
                    let pkt_data = cmd.data.unwrap_or_default();
                    Self::process_packet_entities_filtered(
                        &pkt_data,
                        &mut ctx,
                        &mut field_decode_ctx,
                        &mut packet_buf,
                        class_filter,
                        &mut fp_buf,
                    )?;
                }
                _ => {}
            }
        }

        Ok(())
    }

    /// Parse the entire demo with entity class filtering AND event collection.
    /// Combines `run_to_end_filtered` with `process_packet_events` in a single pass.
    /// The callback receives both the entity context and accumulated events for the tick.
    pub fn run_to_end_with_events_filtered<F>(
        &self,
        class_filter: &std::collections::HashSet<&str>,
        mut on_tick: F,
    ) -> Result<()>
    where
        F: FnMut(&Context, &[GameEvent]),
    {
        let mut ctx = self.parse_init()?;
        let data = &self.data()[HEADER_SIZE..];
        let mut reader = ByteReader::new(data);

        let mut packet_buf = vec![0u8; BUF_SIZE];
        let mut event_packet_buf = vec![0u8; BUF_SIZE];
        let mut body_buf = Vec::with_capacity(BUF_SIZE);
        let mut fp_buf = Vec::with_capacity(256);
        let mut field_decode_ctx = FieldDecodeContext::new(ctx.tick_interval);

        let mut descriptors: HashMap<i32, EventDescriptor> = HashMap::new();
        let mut tick_events: Vec<GameEvent> = Vec::new();

        // Skip past init (up to and including SyncTick)
        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;
            if header.cmd == dem::SYNC_TICK {
                reader.skip(header.body_size as usize)?;
                break;
            }
            if header.cmd == dem::STOP {
                return Ok(());
            }
            reader.skip(header.body_size as usize)?;
        }

        let mut last_tick: i32 = -1;

        while reader.remaining() > 0 {
            let header = Self::read_cmd_header(&mut reader)?;

            // Call callback when tick changes
            if header.tick != last_tick && last_tick >= 0 {
                on_tick(&ctx, &tick_events);
                tick_events.clear();
            }
            last_tick = header.tick;
            ctx.tick = header.tick;

            if header.cmd == dem::STOP {
                // Final callback
                if last_tick >= 0 {
                    on_tick(&ctx, &tick_events);
                }
                break;
            }

            Self::read_cmd_body(&mut reader, &header, &mut body_buf)?;

            match header.cmd {
                dem::FULL_PACKET => {
                    let cmd = CDemoFullPacket::decode(&body_buf[..])?;

                    if let Some(st) = cmd.string_table {
                        ctx.string_tables.do_full_update(st);
                        ctx.string_tables.update_instance_baselines(&ctx.class_info);
                    }

                    if let Some(packet) = cmd.packet {
                        let pkt_data = packet.data.unwrap_or_default();
                        Self::process_packet_entities_filtered(
                            &pkt_data,
                            &mut ctx,
                            &mut field_decode_ctx,
                            &mut packet_buf,
                            class_filter,
                            &mut fp_buf,
                        )?;
                        Self::process_packet_events(
                            &pkt_data,
                            header.tick,
                            &mut descriptors,
                            &mut tick_events,
                            &mut event_packet_buf,
                        )?;
                    }
                }
                dem::PACKET | dem::SIGNON_PACKET => {
                    let cmd = CDemoPacket::decode(&body_buf[..])?;
                    let pkt_data = cmd.data.unwrap_or_default();
                    Self::process_packet_entities_filtered(
                        &pkt_data,
                        &mut ctx,
                        &mut field_decode_ctx,
                        &mut packet_buf,
                        class_filter,
                        &mut fp_buf,
                    )?;
                    Self::process_packet_events(
                        &pkt_data,
                        header.tick,
                        &mut descriptors,
                        &mut tick_events,
                        &mut event_packet_buf,
                    )?;
                }
                _ => {}
            }
        }

        Ok(())
    }

    /// Process a packet's inner messages for entity updates.
    fn process_packet_entities(
        pkt_data: &[u8],
        ctx: &mut Context,
        field_decode_ctx: &mut FieldDecodeContext,
        packet_buf: &mut Vec<u8>,
        fp_buf: &mut Vec<crate::entity::field_path::FieldPath>,
    ) -> Result<()> {
        let mut br = BitReader::new(pkt_data);

        while br.bits_remaining() > 8 {
            let msg_type = br.read_ubitvar()?;
            let size = br.read_uvarint32()? as usize;

            if size > packet_buf.len() {
                packet_buf.resize(size, 0);
            }
            br.read_bytes(&mut packet_buf[..size])?;
            let msg_data = &packet_buf[..size];

            match msg_type {
                svc::CREATE_STRING_TABLE => {
                    let msg = CsvcMsgCreateStringTable::decode(msg_data)?;
                    if ctx.string_tables.handle_create(msg)? {
                        ctx.string_tables.update_instance_baselines(&ctx.class_info);
                    }
                }
                svc::UPDATE_STRING_TABLE => {
                    let msg = CsvcMsgUpdateStringTable::decode(msg_data)?;
                    if ctx.string_tables.handle_update(msg)? {
                        ctx.string_tables.update_instance_baselines(&ctx.class_info);
                    }
                }
                svc::SERVER_INFO => {
                    let msg = CsvcMsgServerInfo::decode(msg_data)?;
                    if let Some(ti) = msg.tick_interval {
                        ctx.tick_interval = ti;
                        field_decode_ctx.tick_interval = ti;
                        let ratio = DEFAULT_TICK_INTERVAL / ti;
                        ctx.full_packet_interval = DEFAULT_FULL_PACKET_INTERVAL * ratio as i32;
                    }
                }
                svc::PACKET_ENTITIES => {
                    let msg = CsvcMsgPacketEntities::decode(msg_data)?;
                    ctx.entities.handle_packet_entities(
                        msg,
                        &ctx.class_info,
                        &ctx.serializers,
                        &ctx.string_tables,
                        field_decode_ctx,
                        fp_buf,
                    )?;
                }
                _ => {}
            }
        }

        Ok(())
    }

    /// Process a packet's inner messages with entity class filtering.
    fn process_packet_entities_filtered(
        pkt_data: &[u8],
        ctx: &mut Context,
        field_decode_ctx: &mut FieldDecodeContext,
        packet_buf: &mut Vec<u8>,
        class_filter: &std::collections::HashSet<&str>,
        fp_buf: &mut Vec<crate::entity::field_path::FieldPath>,
    ) -> Result<()> {
        let mut br = BitReader::new(pkt_data);

        while br.bits_remaining() > 8 {
            let msg_type = br.read_ubitvar()?;
            let size = br.read_uvarint32()? as usize;

            if size > packet_buf.len() {
                packet_buf.resize(size, 0);
            }
            br.read_bytes(&mut packet_buf[..size])?;
            let msg_data = &packet_buf[..size];

            match msg_type {
                svc::CREATE_STRING_TABLE => {
                    let msg = CsvcMsgCreateStringTable::decode(msg_data)?;
                    if ctx.string_tables.handle_create(msg)? {
                        ctx.string_tables.update_instance_baselines(&ctx.class_info);
                    }
                }
                svc::UPDATE_STRING_TABLE => {
                    let msg = CsvcMsgUpdateStringTable::decode(msg_data)?;
                    if ctx.string_tables.handle_update(msg)? {
                        ctx.string_tables.update_instance_baselines(&ctx.class_info);
                    }
                }
                svc::SERVER_INFO => {
                    let msg = CsvcMsgServerInfo::decode(msg_data)?;
                    if let Some(ti) = msg.tick_interval {
                        ctx.tick_interval = ti;
                        field_decode_ctx.tick_interval = ti;
                        let ratio = DEFAULT_TICK_INTERVAL / ti;
                        ctx.full_packet_interval = DEFAULT_FULL_PACKET_INTERVAL * ratio as i32;
                    }
                }
                svc::PACKET_ENTITIES => {
                    let msg = CsvcMsgPacketEntities::decode(msg_data)?;
                    ctx.entities.handle_packet_entities_filtered(
                        msg,
                        &ctx.class_info,
                        &ctx.serializers,
                        &ctx.string_tables,
                        field_decode_ctx,
                        class_filter,
                        fp_buf,
                    )?;
                }
                _ => {}
            }
        }

        Ok(())
    }
}