pbdems2 0.2.2

Game-neutral Source 2 PBDEMS2 demo parsing primitives
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
//! Protobuf-independent demo initialization, seeking, and tick playback.

use std::collections::HashSet;

mod prepared;

pub use prepared::{CheckpointAdapter, PlaybackSegment, PlaybackSession, PreparedPlayback};

use crate::demo::{CommandFrame, Demo, DemoIndex, command};
use crate::entity::field_path::FieldPath;
use crate::entity::{
    ClassEntry, ClassInfo, CreateStringTable, DecodeProfile, EntityContainer, FieldDecodeContext,
    FlattenedSerializer, PacketEntities, SerializerContainer, StringTableContainer,
    StringTableEntry, UpdateStringTable,
};
use crate::error::{Error, Result};
use crate::limits::DecodeLimits;
use crate::packet::PacketMessageIter;

/// Complete game-neutral parser state at a point in demo playback.
#[derive(Clone)]
pub struct ParserState {
    serializers: SerializerContainer,
    class_info: ClassInfo,
    string_tables: StringTableContainer,
    entities: EntityContainer,
    tick_interval: f32,
    tick: i32,
    has_serializers: bool,
    has_class_info: bool,
}

impl ParserState {
    /// Create empty state using a game's default tick interval.
    pub fn new(default_tick_interval: f32) -> Result<Self> {
        validate_tick_interval(default_tick_interval)?;
        Ok(Self {
            serializers: SerializerContainer::default(),
            class_info: ClassInfo::empty(),
            string_tables: StringTableContainer::new(),
            entities: EntityContainer::new(),
            tick_interval: default_tick_interval,
            tick: -1,
            has_serializers: false,
            has_class_info: false,
        })
    }

    /// Parsed flattened serializer graph.
    pub const fn serializers(&self) -> &SerializerContainer {
        &self.serializers
    }

    /// Numeric network class definitions.
    pub const fn class_info(&self) -> &ClassInfo {
        &self.class_info
    }

    /// Current string-table state.
    pub const fn string_tables(&self) -> &StringTableContainer {
        &self.string_tables
    }

    /// Current entity state.
    pub const fn entities(&self) -> &EntityContainer {
        &self.entities
    }

    /// Seconds represented by one game tick.
    pub const fn tick_interval(&self) -> f32 {
        self.tick_interval
    }

    /// Most recently processed tick, or `-1` before playback starts.
    pub const fn tick(&self) -> i32 {
        self.tick
    }

    /// Whether both serializers and class information have been installed.
    pub const fn is_initialized(&self) -> bool {
        self.has_serializers && self.has_class_info
    }

    fn require_initialized(&self) -> Result<()> {
        if !self.has_serializers {
            return Err(Error::Parse {
                context: "flattened serializers were not installed before DEM_SyncTick".into(),
            });
        }
        if !self.has_class_info {
            return Err(Error::Parse {
                context: "class information was not installed before DEM_SyncTick".into(),
            });
        }
        Ok(())
    }

    fn clear_tick_changes(&mut self) {
        self.string_tables.clear_dirty();
        self.entities.clear_updated();
    }
}

const fn segment_replay_end_tick(exclusive_end_tick: i32) -> Option<i32> {
    if exclusive_end_tick == i32::MAX {
        None
    } else {
        Some(exclusive_end_tick.saturating_sub(1))
    }
}

fn validate_tick_interval(tick_interval: f32) -> Result<()> {
    if !tick_interval.is_finite() || tick_interval <= 0.0 {
        return Err(Error::Parse {
            context: format!("invalid tick interval {tick_interval}"),
        });
    }
    Ok(())
}

/// Mutable game-neutral operations available to a protobuf adapter.
///
/// The adapter decodes its generated messages and immediately converts them
/// into these neutral inputs. It never has to manipulate container internals.
pub struct CommandContext<'state, 'filter> {
    state: &'state mut ParserState,
    field_decode_context: &'state mut FieldDecodeContext,
    field_paths: &'state mut Vec<FieldPath>,
    limits: DecodeLimits,
    class_filter: Option<&'filter HashSet<&'filter str>>,
}

impl<'state, 'filter> CommandContext<'state, 'filter> {
    /// Read current parser state while handling a command.
    pub const fn state(&self) -> &ParserState {
        self.state
    }

    /// Limits applied to adapter-decoded message sizes and neutral operations.
    pub const fn limits(&self) -> DecodeLimits {
        self.limits
    }

    /// Validate an inner packet-message payload before an adapter allocates it.
    pub fn check_packet_message_size(&self, size: usize) -> Result<()> {
        self.limits.ensure(
            "inner packet message",
            size,
            self.limits.max_packet_message_bytes(),
        )
    }

    /// Iterate the game-neutral message framing inside a packet payload.
    ///
    /// The adapter still decides which generated protobuf type corresponds to
    /// each message identifier. Unaligned payloads can be copied into one
    /// reusable buffer with
    /// [PacketMessageFrame::copy_payload](crate::packet::PacketMessageFrame::copy_payload).
    pub fn packet_messages<'packet>(&self, data: &'packet [u8]) -> PacketMessageIter<'packet> {
        PacketMessageIter::with_limits(data, self.limits)
    }

    /// Parse and install flattened serializers.
    pub fn install_serializers(
        &mut self,
        serializers: FlattenedSerializer,
        profile: DecodeProfile,
    ) -> Result<()> {
        self.state.serializers =
            SerializerContainer::parse_with_limits(serializers, profile, &self.limits)?;
        self.state.has_serializers = true;
        Ok(())
    }

    /// Validate and install network classes.
    pub fn install_class_info(
        &mut self,
        classes: impl IntoIterator<Item = ClassEntry>,
    ) -> Result<()> {
        self.state.class_info = ClassInfo::try_from_entries_with_limits(classes, &self.limits)?;
        self.state.has_class_info = true;
        self.state.string_tables.update_instance_baselines();
        Ok(())
    }

    /// Update the tick interval reported by server-info.
    pub fn set_tick_interval(&mut self, tick_interval: f32) -> Result<()> {
        validate_tick_interval(tick_interval)?;
        self.state.tick_interval = tick_interval;
        self.field_decode_context.set_tick_interval(tick_interval);
        Ok(())
    }

    /// Create a string table from a neutral adapter message.
    pub fn create_string_table(&mut self, table: CreateStringTable) -> Result<()> {
        let baseline = self
            .state
            .string_tables
            .handle_create_with_limits(table, &self.limits)?;
        if baseline {
            self.state.string_tables.update_instance_baselines();
        }
        Ok(())
    }

    /// Apply an incremental string-table update.
    pub fn update_string_table(&mut self, update: UpdateStringTable) -> Result<()> {
        let baseline = self
            .state
            .string_tables
            .handle_update_with_limits(update, &self.limits)?;
        if baseline {
            self.state.string_tables.update_instance_baselines();
        }
        Ok(())
    }

    /// Apply the string-table snapshot carried by a full packet.
    pub fn apply_full_string_tables(
        &mut self,
        tables: impl IntoIterator<Item = (String, Vec<StringTableEntry>)>,
    ) -> Result<()> {
        self.state
            .string_tables
            .do_full_update_with_limits(tables, &self.limits)?;
        self.state.string_tables.update_instance_baselines();
        Ok(())
    }

    /// Apply a packet-entities message, honoring the playback class filter.
    pub fn apply_packet_entities(&mut self, packet: PacketEntities<'_>) -> Result<()> {
        let state = &mut self.state;
        if let Some(filter) = self.class_filter {
            state.entities.handle_packet_entities_filtered(
                packet,
                &state.class_info,
                &state.serializers,
                &state.string_tables,
                self.field_decode_context,
                filter,
                self.field_paths,
            )
        } else {
            state.entities.handle_packet_entities(
                packet,
                &state.class_info,
                &state.serializers,
                &state.string_tables,
                self.field_decode_context,
                self.field_paths,
            )
        }
    }
}

/// Game-specific protobuf bridge used by [`DemoParser`].
///
/// Implementations normally match on `frame.header().cmd`, decode a generated
/// protobuf from `body`, convert it to neutral pbdems2 values, and call methods
/// on `context`. The associated error can wrap both protobuf errors and
/// [`crate::Error`]; the `From<Error>` bound lets the driver propagate framing
/// and limit failures without stringifying them.
pub trait DemoAdapter {
    /// Failure type produced by the adapter, able to carry a [`crate::Error`].
    type Error: From<Error>;

    /// Handle one decompressed command from the demo stream.
    ///
    /// `body` is the decoded payload for `frame`; commands the adapter does
    /// not care about should return `Ok(())` without touching `context`.
    fn handle_command(
        &mut self,
        frame: &CommandFrame<'_>,
        body: &[u8],
        context: &mut CommandContext<'_, '_>,
    ) -> std::result::Result<(), Self::Error>;
}

/// Borrowed neutral parser driver for one validated PBDEMS2 file.
#[derive(Debug, Clone, Copy)]
pub struct DemoParser<'a> {
    demo: Demo<'a>,
}

impl<'a> DemoParser<'a> {
    /// Validate a complete demo using default limits.
    pub fn new(data: &'a [u8]) -> Result<Self> {
        Ok(Self {
            demo: Demo::new(data)?,
        })
    }

    /// Validate a complete demo using explicit limits.
    pub fn with_limits(data: &'a [u8], limits: DecodeLimits) -> Result<Self> {
        Ok(Self {
            demo: Demo::with_limits(data, limits)?,
        })
    }

    /// The underlying command-stream view.
    pub const fn demo(&self) -> &Demo<'a> {
        &self.demo
    }

    /// Build the header-only seek index.
    pub fn index(&self) -> Result<DemoIndex> {
        self.demo.index()
    }

    /// Decode signon state through `DEM_SyncTick`.
    pub fn initial_state<A: DemoAdapter>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
    ) -> std::result::Result<ParserState, A::Error> {
        self.initialize(adapter, default_tick_interval)
            .map(|(state, _)| state)
    }

    /// Decode all post-signon commands and invoke `on_tick` once per completed tick.
    pub fn run_to_end<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState),
    {
        let mut on_tick = on_tick;
        self.try_run_to_end(adapter, default_tick_interval, |state| {
            on_tick(state);
            Ok(())
        })
    }

    /// Decode all commands with a callback that can abort playback with an error.
    ///
    /// The callback uses the adapter's application error type so a consumer can
    /// propagate output, database, cancellation, or other processing failures
    /// without erasing either those errors or parser errors.
    pub fn try_run_to_end<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState) -> std::result::Result<(), A::Error>,
    {
        let mut on_tick = on_tick;
        self.run_to_end_impl(adapter, default_tick_interval, None, |state, _| {
            on_tick(state)
        })
    }

    /// Decode all commands and expose game-specific adapter state at each tick.
    pub fn run_to_end_with_adapter<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState, &mut A),
    {
        let mut on_tick = on_tick;
        self.try_run_to_end_with_adapter(adapter, default_tick_interval, |state, adapter| {
            on_tick(state, adapter);
            Ok(())
        })
    }

    /// Fallible playback with mutable adapter access at each completed tick.
    ///
    /// This supports consumers that collect game-specific state, such as
    /// per-tick events, inside their protobuf adapter.
    pub fn try_run_to_end_with_adapter<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState, &mut A) -> std::result::Result<(), A::Error>,
    {
        self.run_to_end_impl(adapter, default_tick_interval, None, on_tick)
    }

    /// Decode all commands while only materializing entities in `class_filter`.
    pub fn run_to_end_filtered<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        class_filter: &HashSet<&str>,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState),
    {
        let mut on_tick = on_tick;
        self.try_run_to_end_filtered(adapter, default_tick_interval, class_filter, |state| {
            on_tick(state);
            Ok(())
        })
    }

    /// Filter entities and allow the per-tick callback to abort with an error.
    pub fn try_run_to_end_filtered<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        class_filter: &HashSet<&str>,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState) -> std::result::Result<(), A::Error>,
    {
        let mut on_tick = on_tick;
        self.run_to_end_impl(
            adapter,
            default_tick_interval,
            Some(class_filter),
            |state, _| on_tick(state),
        )
    }

    /// Filter entities and expose mutable adapter state at each completed tick.
    pub fn run_to_end_filtered_with_adapter<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        class_filter: &HashSet<&str>,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState, &mut A),
    {
        let mut on_tick = on_tick;
        self.try_run_to_end_filtered_with_adapter(
            adapter,
            default_tick_interval,
            class_filter,
            |state, adapter| {
                on_tick(state, adapter);
                Ok(())
            },
        )
    }

    /// Fallible filtered playback with mutable adapter access at each tick.
    pub fn try_run_to_end_filtered_with_adapter<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        class_filter: &HashSet<&str>,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState, &mut A) -> std::result::Result<(), A::Error>,
    {
        self.run_to_end_impl(adapter, default_tick_interval, Some(class_filter), on_tick)
    }

    /// Restore the latest full packet at or before `target_tick`, then replay deltas.
    pub fn parse_to_tick<A: DemoAdapter>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        target_tick: i32,
    ) -> std::result::Result<ParserState, A::Error> {
        let (mut state, stream_start) = self.initialize(adapter, default_tick_interval)?;
        let index = self.demo.index().map_err(A::Error::from)?;
        let start = index
            .full_packet_at_or_before(target_tick)
            .map(|position| position.offset())
            .or(stream_start);
        if let Some(start) = start {
            self.replay(
                adapter,
                &mut state,
                start,
                Some(target_tick),
                None,
                |_, _| Ok(()),
            )?;
        }
        Ok(state)
    }

    /// Cold-start one segment from signon or a full-packet keyframe.
    ///
    /// A full-packet restart is exact only for entity classes that the game
    /// fully re-keyframes in that snapshot. Consumers are responsible for
    /// choosing a compatible `class_filter`; pbdems2 cannot infer which
    /// classes carry unsnapshotted state between keyframes.
    pub fn decode_segment<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        start: Option<usize>,
        end_tick: i32,
        class_filter: &HashSet<&str>,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState),
    {
        let mut on_tick = on_tick;
        self.try_decode_segment(
            adapter,
            default_tick_interval,
            start,
            end_tick,
            class_filter,
            |state| {
                on_tick(state);
                Ok(())
            },
        )
    }

    /// Decode a segment with a callback that can abort playback with an error.
    pub fn try_decode_segment<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        start: Option<usize>,
        end_tick: i32,
        class_filter: &HashSet<&str>,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState) -> std::result::Result<(), A::Error>,
    {
        let mut on_tick = on_tick;
        self.try_decode_segment_with_adapter(
            adapter,
            default_tick_interval,
            start,
            end_tick,
            class_filter,
            |state, _| on_tick(state),
        )
    }

    /// Decode one segment and expose mutable adapter state at each tick.
    pub fn decode_segment_with_adapter<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        start: Option<usize>,
        end_tick: i32,
        class_filter: &HashSet<&str>,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState, &mut A),
    {
        let mut on_tick = on_tick;
        self.try_decode_segment_with_adapter(
            adapter,
            default_tick_interval,
            start,
            end_tick,
            class_filter,
            |state, adapter| {
                on_tick(state, adapter);
                Ok(())
            },
        )
    }

    /// Fallible segment playback with mutable adapter access at each tick.
    pub fn try_decode_segment_with_adapter<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        start: Option<usize>,
        end_tick: i32,
        class_filter: &HashSet<&str>,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState, &mut A) -> std::result::Result<(), A::Error>,
    {
        let (mut state, stream_start) = self.initialize(adapter, default_tick_interval)?;
        if let Some(start) = start.or(stream_start) {
            self.replay(
                adapter,
                &mut state,
                start,
                segment_replay_end_tick(end_tick),
                Some(class_filter),
                on_tick,
            )?;
        }
        Ok(state)
    }

    fn run_to_end_impl<A, F>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
        class_filter: Option<&HashSet<&str>>,
        on_tick: F,
    ) -> std::result::Result<ParserState, A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState, &mut A) -> std::result::Result<(), A::Error>,
    {
        let (mut state, stream_start) = self.initialize(adapter, default_tick_interval)?;
        if let Some(start) = stream_start {
            self.replay(adapter, &mut state, start, None, class_filter, on_tick)?;
        }
        Ok(state)
    }

    fn initialize<A: DemoAdapter>(
        &self,
        adapter: &mut A,
        default_tick_interval: f32,
    ) -> std::result::Result<(ParserState, Option<usize>), A::Error> {
        let limits = self.demo.limits();
        let mut state = ParserState::new(default_tick_interval).map_err(A::Error::from)?;
        let mut body = Vec::new();
        let mut field_decode_context =
            FieldDecodeContext::with_limits(default_tick_interval, limits);
        let mut field_paths = Vec::new();
        let mut stream_start = None;

        for frame in self.demo.commands() {
            let frame = frame.map_err(A::Error::from)?;
            match frame.header().cmd {
                command::STOP => break,
                command::SYNC_TICK => {
                    stream_start = Some(frame.end_offset());
                    break;
                }
                _ => {}
            }
            frame.decode_body(&mut body).map_err(A::Error::from)?;
            let mut context = CommandContext {
                state: &mut state,
                field_decode_context: &mut field_decode_context,
                field_paths: &mut field_paths,
                limits,
                class_filter: None,
            };
            adapter.handle_command(&frame, &body, &mut context)?;
        }

        state.require_initialized().map_err(A::Error::from)?;
        state.string_tables.update_instance_baselines();
        Ok((state, stream_start))
    }

    #[allow(clippy::too_many_arguments)]
    fn replay<A, F>(
        &self,
        adapter: &mut A,
        state: &mut ParserState,
        start: usize,
        end_tick: Option<i32>,
        class_filter: Option<&HashSet<&str>>,
        mut on_tick: F,
    ) -> std::result::Result<(), A::Error>
    where
        A: DemoAdapter,
        F: FnMut(&ParserState, &mut A) -> std::result::Result<(), A::Error>,
    {
        let limits = self.demo.limits();
        let commands = self.demo.commands_from(start).map_err(A::Error::from)?;
        let mut body = Vec::new();
        let mut field_decode_context = FieldDecodeContext::with_limits(state.tick_interval, limits);
        let mut field_paths = Vec::new();
        let mut last_tick = None;
        let mut emitted_final_tick = false;

        for frame in commands {
            let frame = frame.map_err(A::Error::from)?;
            let header = frame.header();
            if end_tick.is_some_and(|end| header.tick > end) && header.cmd != command::STOP {
                break;
            }

            if last_tick.is_some_and(|last| last != header.tick) {
                on_tick(state, adapter)?;
                state.clear_tick_changes();
            }
            last_tick = Some(header.tick);
            state.tick = header.tick;

            if header.cmd == command::STOP {
                if header.tick >= 0 {
                    on_tick(state, adapter)?;
                    emitted_final_tick = true;
                }
                break;
            }

            frame.decode_body(&mut body).map_err(A::Error::from)?;
            let mut context = CommandContext {
                state,
                field_decode_context: &mut field_decode_context,
                field_paths: &mut field_paths,
                limits,
                class_filter,
            };
            adapter.handle_command(&frame, &body, &mut context)?;
        }

        if !emitted_final_tick && last_tick.is_some_and(|tick| tick >= 0) {
            on_tick(state, adapter)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::demo::{HEADER_SIZE, MAGIC};
    use crate::entity::{BareCharEncoding, FlattenedSerializerDefinition, PreciseQAngleMode};

    #[derive(Default)]
    struct Adapter;

    impl DemoAdapter for Adapter {
        type Error = Error;

        fn handle_command(
            &mut self,
            frame: &CommandFrame<'_>,
            _body: &[u8],
            context: &mut CommandContext<'_, '_>,
        ) -> Result<()> {
            match frame.header().cmd {
                command::SEND_TABLES => context.install_serializers(
                    FlattenedSerializer {
                        serializers: vec![FlattenedSerializerDefinition {
                            serializer_name_sym: Some(0),
                            fields_index: vec![],
                        }],
                        symbols: vec!["CTest".into()],
                        fields: vec![],
                    },
                    DecodeProfile::new(
                        BareCharEncoding::NullTerminatedString,
                        PreciseQAngleMode::Centered,
                    ),
                ),
                command::CLASS_INFO => {
                    context.install_class_info([ClassEntry::new(0, "CTest", "CTest")])
                }
                _ => Ok(()),
            }
        }
    }

    fn push_command(bytes: &mut Vec<u8>, command: u8, tick: u8) {
        bytes.extend_from_slice(&[command, tick, 0]);
    }

    fn fixture() -> Vec<u8> {
        let mut bytes = Vec::from(MAGIC);
        bytes.resize(HEADER_SIZE, 0);
        push_command(&mut bytes, command::SEND_TABLES as u8, 0);
        push_command(&mut bytes, command::CLASS_INFO as u8, 0);
        push_command(&mut bytes, command::SYNC_TICK as u8, 0);
        push_command(&mut bytes, command::PACKET as u8, 1);
        push_command(&mut bytes, command::PACKET as u8, 2);
        push_command(&mut bytes, command::STOP as u8, 3);
        bytes
    }

    #[test]
    fn initializes_and_emits_completed_ticks() {
        let bytes = fixture();
        let parser = DemoParser::new(&bytes).expect("valid demo");
        let mut ticks = Vec::new();
        let state = parser
            .run_to_end(&mut Adapter, 1.0 / 64.0, |state| ticks.push(state.tick()))
            .expect("valid playback");
        assert!(state.is_initialized());
        assert_eq!(ticks, [1, 2, 3]);
    }

    #[test]
    fn parse_to_tick_stops_after_target() {
        let bytes = fixture();
        let state = DemoParser::new(&bytes)
            .expect("valid demo")
            .parse_to_tick(&mut Adapter, 1.0 / 64.0, 1)
            .expect("valid playback");
        assert_eq!(state.tick(), 1);
    }

    #[test]
    fn fallible_tick_callback_stops_and_preserves_the_error() {
        let bytes = fixture();
        let parser = DemoParser::new(&bytes).expect("valid demo");
        let mut ticks = Vec::new();
        let error = parser
            .try_run_to_end(&mut Adapter, 1.0 / 64.0, |state| {
                ticks.push(state.tick());
                if state.tick() == 2 {
                    return Err(Error::Parse {
                        context: "tick consumer failed".into(),
                    });
                }
                Ok(())
            })
            .err()
            .expect("callback failure must abort playback");

        assert_eq!(ticks, [1, 2]);
        assert!(matches!(
            error,
            Error::Parse { context } if context == "tick consumer failed"
        ));
    }

    #[test]
    fn fallible_filtered_callback_preserves_the_error() {
        let bytes = fixture();
        let parser = DemoParser::new(&bytes).expect("valid demo");
        let filter = HashSet::from(["CTest"]);
        let error = parser
            .try_run_to_end_filtered(&mut Adapter, 1.0 / 64.0, &filter, |_| -> Result<()> {
                Err(Error::Parse {
                    context: "filtered consumer failed".into(),
                })
            })
            .err()
            .expect("callback failure must abort playback");

        assert!(matches!(
            error,
            Error::Parse { context } if context == "filtered consumer failed"
        ));
    }

    #[test]
    fn fallible_segment_callback_preserves_the_error() {
        let bytes = fixture();
        let parser = DemoParser::new(&bytes).expect("valid demo");
        let filter = HashSet::new();
        let error = parser
            .try_decode_segment(&mut Adapter, 1.0 / 64.0, None, 4, &filter, |_| {
                Err(Error::Parse {
                    context: "segment consumer failed".into(),
                })
            })
            .err()
            .expect("callback failure must abort playback");

        assert!(matches!(
            error,
            Error::Parse { context } if context == "segment consumer failed"
        ));
    }

    #[test]
    fn rejects_missing_initialization_messages() {
        let mut bytes = Vec::from(MAGIC);
        bytes.resize(HEADER_SIZE, 0);
        push_command(&mut bytes, command::SYNC_TICK as u8, 0);
        assert!(
            DemoParser::new(&bytes)
                .expect("valid framing")
                .initial_state(&mut Adapter, 1.0 / 64.0)
                .is_err()
        );
    }
}