halo_api 0.3.0

Unofficial Halo Infinite REST API client for Rust (CSR, service record, match history, and more).
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
//! Experimental decoder for Halo Infinite Theater film chunks.

use std::collections::{BTreeMap, BTreeSet};

use super::models::{FilmChunkData, MatchStats};

const PLAYER_MARKERS: [[u8; 2]; 2] = [[0x2d, 0xc0], [0x25, 0xc0]];
const REGISTRY_SLOT_SIZE: usize = 260;
const REGISTRY_BLOCK_SLOTS: usize = 64;
const REGISTRY_BLOCK_SIZE: usize = REGISTRY_SLOT_SIZE * REGISTRY_BLOCK_SLOTS;

/// Ordered replication components for one ECS entity archetype.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilmArchetype {
    pub index: usize,
    pub components: Vec<String>,
}

/// Entity-component schema serialized in a Theater film's bootstrap chunk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilmRegistry {
    pub archetypes: Vec<FilmArchetype>,
}

impl FilmRegistry {
    pub fn archetype(&self, index: usize) -> Option<&FilmArchetype> {
        self.archetypes.get(index)
    }
}

/// Parses the fixed-width ECS component registry from the film bootstrap chunk.
pub fn decode_registry(chunks: &[FilmChunkData]) -> Option<FilmRegistry> {
    let data = &chunks
        .iter()
        .find(|chunk| chunk.metadata.chunk_type == 1)?
        .data;
    let archetypes = data
        .chunks_exact(REGISTRY_BLOCK_SIZE)
        .enumerate()
        .map(|(index, block)| {
            let components = block
                .chunks_exact(REGISTRY_SLOT_SIZE)
                .map(registry_slot_name)
                .take_while(Option::is_some)
                .flatten()
                .collect();
            FilmArchetype { index, components }
        })
        .collect();
    Some(FilmRegistry { archetypes })
}

fn registry_slot_name(slot: &[u8]) -> Option<String> {
    let bytes = slot.get(8..)?;
    let end = bytes
        .iter()
        .position(|byte| *byte == 0)
        .unwrap_or(bytes.len());
    let name = bytes.get(..end)?;
    if name.is_empty() || !name.iter().all(|byte| byte.is_ascii_graphic()) {
        return None;
    }
    Some(String::from_utf8(name.to_vec()).expect("validated ASCII component name"))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FilmEntityState {
    full_id: u32,
    archetype_index: u8,
}

/// Persistent entity bindings required to interpret FRAME delta records.
#[derive(Debug, Clone, Default)]
pub struct FilmWorld {
    entities: BTreeMap<u32, FilmEntityState>,
}

impl FilmWorld {
    pub fn bind(&mut self, full_id: u32, archetype_index: u8) {
        self.entities.insert(
            full_id & 0x3fff_ffff,
            FilmEntityState {
                full_id,
                archetype_index,
            },
        );
    }

    pub fn unbind(&mut self, slot: u32) {
        self.entities.remove(&slot);
    }

    pub fn archetype_index(&self, slot: u32) -> Option<u8> {
        self.entities.get(&slot).map(|state| state.archetype_index)
    }

    pub fn full_id(&self, slot: u32) -> Option<u32> {
        self.entities.get(&slot).map(|state| state.full_id)
    }

    pub fn len(&self) -> usize {
        self.entities.len()
    }

    pub fn is_empty(&self) -> bool {
        self.entities.is_empty()
    }
}

#[derive(Debug, Clone)]
pub struct FilmBitReader<'a> {
    data: &'a [u8],
    position: usize,
}

impl<'a> FilmBitReader<'a> {
    pub fn new(data: &'a [u8]) -> Self {
        Self { data, position: 0 }
    }

    pub fn read(&mut self, width: usize) -> Option<u64> {
        if width > 64 || self.position.checked_add(width)? > self.data.len() * 8 {
            return None;
        }
        let mut value = 0u64;
        for _ in 0..width {
            value = (value << 1) | u64::from(bit_at(self.data, self.position));
            self.position += 1;
        }
        Some(value)
    }

    pub const fn position(&self) -> usize {
        self.position
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FilmRecordKind {
    End,
    New,
    Delete,
    Delta,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilmRecordHeader {
    pub kind: FilmRecordKind,
    pub full_id: Option<u32>,
    pub slot: Option<u32>,
    pub header_bits: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilmDeltaHeader {
    pub record: FilmRecordHeader,
    pub component_mask: u64,
    pub data_bit_offset: usize,
}

/// Decodes the first DELTA record through its component-presence mask.
pub fn decode_first_delta_header(payload: &[u8]) -> Option<FilmDeltaHeader> {
    let record = decode_frame_record_header(payload)?;
    if record.kind != FilmRecordKind::Delta {
        return None;
    }
    let mut reader = FilmBitReader::new(payload);
    reader.read(record.header_bits)?;
    let component_mask = if reader.read(1)? != 0 {
        // Component bitsets are serialized component-0 first. `FilmBitReader`
        // returns that first bit as the high bit of a u64, whereas the sparse
        // representation below uses component indexes as normal bit positions.
        reader.read(64)?.reverse_bits()
    } else {
        let count = reader.read(3)? as usize;
        let mut mask = 0u64;
        for _ in 0..count {
            mask |= 1u64 << reader.read(6)?;
        }
        mask
    };
    Some(FilmDeltaHeader {
        record,
        component_mask,
        data_bit_offset: reader.position(),
    })
}

/// Decodes the prefix-coded header of the first entity record in a FRAME payload.
pub fn decode_frame_record_header(payload: &[u8]) -> Option<FilmRecordHeader> {
    decode_frame_record_header_with_id_width(payload, 11)
}

fn decode_frame_record_header_with_id_width(
    payload: &[u8],
    id_width: usize,
) -> Option<FilmRecordHeader> {
    let mut reader = FilmBitReader::new(payload);
    let kind = if reader.read(1)? != 0 {
        FilmRecordKind::Delta
    } else {
        match reader.read(2)? {
            0 => FilmRecordKind::End,
            1 => FilmRecordKind::New,
            2 => FilmRecordKind::Delete,
            3 => FilmRecordKind::Delta,
            _ => unreachable!(),
        }
    };
    if kind == FilmRecordKind::End {
        return Some(FilmRecordHeader {
            kind,
            full_id: None,
            slot: None,
            header_bits: reader.position(),
        });
    }
    let low = reader.read(id_width)? as u32;
    let tag = reader.read(2)? as u32;
    let full_id = (tag << 30) | low;
    Some(FilmRecordHeader {
        kind,
        full_id: Some(full_id),
        slot: Some(low),
        header_bits: reader.position(),
    })
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FilmPacket {
    pub chunk_index: i32,
    pub packet_type: u16,
    pub byte_2: u8,
    pub byte_3: u8,
    pub payload_offset: usize,
    pub payload_size: usize,
    pub timestamp_us: u64,
}

/// Indexes the byte-aligned packet stream inside decompressed replication chunks.
pub fn index_packets(chunks: &[FilmChunkData]) -> Vec<FilmPacket> {
    let mut packets = Vec::new();
    for chunk in chunks.iter().filter(|chunk| chunk.metadata.chunk_type == 2) {
        let mut header_offset = 0usize;
        while let Some(header) = chunk.data.get(header_offset..header_offset + 16) {
            let packet_type = u16::from_le_bytes([header[0], header[1]]);
            let payload_size =
                u32::from_le_bytes(header[4..8].try_into().expect("four size bytes")) as usize;
            let timestamp_us =
                u64::from_le_bytes(header[8..16].try_into().expect("eight timestamp bytes"));
            let payload_offset = header_offset + 16;
            let Some(next_header) = payload_offset.checked_add(payload_size) else {
                break;
            };
            if next_header > chunk.data.len() {
                break;
            }
            packets.push(FilmPacket {
                chunk_index: chunk.metadata.index,
                packet_type,
                byte_2: header[2],
                byte_3: header[3],
                payload_offset,
                payload_size,
                timestamp_us,
            });
            header_offset = next_header;
            if packet_type == 7 {
                break;
            }
        }
    }
    packets
}

fn bit_at(data: &[u8], position: usize) -> bool {
    data.get(position / 8)
        .is_some_and(|byte| byte & (1 << (7 - position % 8)) != 0)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilmPlayer {
    pub xuid: u64,
    pub gamertag: String,
}

/// Finds the film's 5-bit replication index for each known human player.
pub fn decode_player_indices(
    chunks: &[FilmChunkData],
    players: &[FilmPlayer],
) -> BTreeMap<u64, u8> {
    let mut indices = BTreeMap::new();
    for chunk in chunks.iter().filter(|chunk| chunk.metadata.chunk_type == 2) {
        for player in players {
            if indices.contains_key(&player.xuid) {
                continue;
            }
            let xuid = player.xuid.to_le_bytes();
            let Some(position) = find_bit_pattern(&chunk.data, &xuid).into_iter().next() else {
                continue;
            };
            let Some(index_position) = position.checked_sub(5) else {
                continue;
            };
            if let Some(bits) = extract_bits(&chunk.data, index_position, 5) {
                indices.insert(player.xuid, bits[0] >> 3);
            }
        }
    }
    indices
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilmEventKind {
    Mode,
    Death,
    Kill,
    Medal,
    Other(u8),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilmMedal {
    Known { id: u8, name: &'static str },
    Unknown(u8),
}

/// Known film-medal IDs.
pub const KNOWN_FILM_MEDALS: &[(u8, &str)] = &[
    (0, "Double Kill"),
    (1, "Triple Kill"),
    (2, "Overkill"),
    (3, "Killtacular"),
    (4, "Killtrocity"),
    (5, "Killamanjaro"),
    (6, "Killtastrophe"),
    (7, "Killpocalypse"),
    (8, "Killionaire"),
    (9, "Killing Spree"),
    (10, "Killing Frenzy"),
    (11, "Running Riot"),
    (12, "Rampage"),
    (13, "Perfection"),
    (26, "Killjoy"),
    (27, "Nightmare"),
    (28, "Boogeyman"),
    (29, "Grim Reaper"),
    (30, "Demon"),
    (31, "Flawless Victory"),
    (32, "Steaktacular"),
    (36, "Stopped Short"),
    (37, "Flag Joust"),
    (38, "Goal Line Stand"),
    (39, "Necromancer"),
    (43, "Ace"),
    (44, "Extermination"),
    (45, "Sole Survivor"),
    (46, "Untainted"),
    (47, "Blight"),
    (48, "Disease"),
    (49, "Plague"),
    (51, "Pestilence"),
    (53, "Culling"),
    (54, "Cleansing"),
    (55, "Purge"),
    (56, "Purification"),
    (57, "Divine Intervention"),
    (58, "Zombie Slayer"),
    (59, "Undead Hunter"),
    (60, "Hell's Janitor"),
    (61, "The Sickness"),
    (62, "Spotter"),
    (63, "Treasure Hunter"),
    (64, "Saboteur"),
    (65, "Wingman"),
    (66, "Wheelman"),
    (67, "Gunner"),
    (68, "Driver"),
    (69, "Pilot"),
    (70, "Tanker"),
    (71, "Rifleman"),
    (72, "Bomber"),
    (73, "Grenadier"),
    (74, "Boxer"),
    (75, "Warrior"),
    (76, "Gunslinger"),
    (77, "Scattergunner"),
    (78, "Sharpshooter"),
    (79, "Marksman"),
    (80, "Heavy"),
    (81, "Bodyguard"),
    (82, "Back Smack"),
    (83, "Nuclear Football"),
    (84, "Boom Block"),
    (85, "Bulltrue"),
    (86, "Cluster Luck"),
    (87, "Dogfight"),
    (88, "Harpoon"),
    (89, "Mind the Gap"),
    (90, "Ninja"),
    (91, "Odin's Raven"),
    (92, "Pancake"),
    (93, "Quigley"),
    (94, "Remote Detonation"),
    (95, "Return to Sender"),
    (96, "Rideshare"),
    (97, "Skyjack"),
    (98, "Stick"),
    (99, "Tag & Bag"),
    (108, "Snipe"),
    (109, "Perfect"),
    (114, "No Scope"),
    (127, "From the Grave"),
    (128, "From the Void"),
    (129, "Grapple-jack"),
    (130, "Hold This"),
    (131, "Last Shot"),
    (132, "Lawnmower"),
    (133, "Mount Up"),
    (134, "Off the Rack"),
    (135, "Quick Draw"),
    (137, "Pineapple Express"),
    (138, "Ramming Speed"),
    (139, "Reclaimer"),
    (140, "Shot Caller"),
    (141, "Yard Sale"),
    (142, "Special Delivery"),
    (146, "Fumble"),
    (148, "Straight Balling"),
    (151, "Always Rotating"),
    (152, "Hill Guardian"),
    (153, "Clock Stop"),
    (154, "Secure Line"),
    (156, "Splatter"),
    (162, "All That Juice"),
    (163, "Great Journey"),
    (165, "Breacher"),
    (166, "Mounted"),
    (168, "Counter-snipe"),
];

impl FilmMedal {
    pub fn from_id(id: u8) -> Self {
        KNOWN_FILM_MEDALS
            .iter()
            .find(|(known_id, _)| *known_id == id)
            .map_or(Self::Unknown(id), |(_, name)| Self::Known { id, name })
    }

    pub const fn name(self) -> &'static str {
        match self {
            Self::Known { name, .. } => name,
            Self::Unknown(_) => "Unknown medal",
        }
    }
}

impl FilmEventKind {
    pub const fn from_fields(code: u8, medal_flag: u8) -> Self {
        if medal_flag != 0 {
            return Self::Medal;
        }
        match code {
            10 => Self::Mode,
            20 => Self::Death,
            50 => Self::Kill,
            other => Self::Other(other),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilmEvent {
    pub xuid: u64,
    pub gamertag: String,
    pub timestamp_ms: u32,
    pub kind: FilmEventKind,
    pub medal_flag: u8,
    pub metadata: u8,
}

/// Counts of event categories represented in a Theater-film summary.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FilmEventCounts {
    pub kills: usize,
    pub deaths: usize,
    pub medals: usize,
}

/// A player's decoded summary-event counts compared with Halo's match record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilmPlayerEventValidation {
    pub xuid: u64,
    pub gamertag: Option<String>,
    pub decoded: FilmEventCounts,
    pub match_stats: FilmEventCounts,
}

impl FilmPlayerEventValidation {
    /// Returns whether this player's decoded counts agree with the match record.
    pub fn matches_stats(&self) -> bool {
        self.decoded == self.match_stats
    }
}

/// Per-player comparison between a Theater film's summary events and match stats.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FilmEventValidation {
    pub players: Vec<FilmPlayerEventValidation>,
}

impl FilmEventValidation {
    /// Returns whether every represented human player has matching event counts.
    pub fn matches_stats(&self) -> bool {
        self.players
            .iter()
            .all(FilmPlayerEventValidation::matches_stats)
    }
}

/// Decoded highlight events with their comparison to the match-statistics API.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilmEventReport {
    pub events: Vec<FilmEvent>,
    pub validation: FilmEventValidation,
}

impl FilmEvent {
    pub fn medal(&self) -> Option<FilmMedal> {
        if matches!(self.kind, FilmEventKind::Medal) {
            Some(FilmMedal::from_id(self.metadata))
        } else {
            None
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FilmDecodeDiagnostics {
    pub player_markers: usize,
    pub markers_with_zero_padding: usize,
    pub decoded_gamertags: usize,
}

pub fn decode_diagnostics(chunks: &[FilmChunkData]) -> FilmDecodeDiagnostics {
    let mut diagnostics = FilmDecodeDiagnostics::default();
    for chunk in chunks.iter().filter(|chunk| chunk.metadata.chunk_type != 3) {
        for marker in PLAYER_MARKERS {
            for marker_position in find_bit_pattern(&chunk.data, &marker) {
                diagnostics.player_markers += 1;
                let Some(xuid_position) = marker_position.checked_sub(8 * 8) else {
                    continue;
                };
                let Some(padding_position) = xuid_position.checked_sub(21 * 8) else {
                    continue;
                };
                if bits_are_zero(&chunk.data, padding_position, 21 * 8) {
                    diagnostics.markers_with_zero_padding += 1;
                    let Some(gamertag_position) = padding_position.checked_sub(32 * 8) else {
                        continue;
                    };
                    if extract_bits(&chunk.data, gamertag_position, 32 * 8)
                        .is_some_and(|bytes| !decode_utf16(&bytes).is_empty())
                    {
                        diagnostics.decoded_gamertags += 1;
                    }
                }
            }
        }
    }
    diagnostics
}

pub fn decode_players(chunks: &[FilmChunkData]) -> Vec<FilmPlayer> {
    let mut players = BTreeMap::new();
    for chunk in chunks.iter().filter(|chunk| chunk.metadata.chunk_type != 3) {
        for marker in PLAYER_MARKERS {
            for marker_position in find_bit_pattern(&chunk.data, &marker) {
                let Some(xuid_position) = marker_position.checked_sub(8 * 8) else {
                    continue;
                };
                let Some(padding_position) = xuid_position.checked_sub(21 * 8) else {
                    continue;
                };
                let Some(gamertag_position) = padding_position.checked_sub(32 * 8) else {
                    continue;
                };
                let Some(xuid_bytes) = extract_bits(&chunk.data, xuid_position, 8 * 8) else {
                    continue;
                };
                if !bits_are_zero(&chunk.data, padding_position, 21 * 8) {
                    continue;
                }
                let xuid = u64::from_le_bytes(xuid_bytes.try_into().expect("eight XUID bytes"));
                if xuid == 0 {
                    continue;
                }
                let Some(gamertag_bytes) = extract_bits(&chunk.data, gamertag_position, 32 * 8)
                else {
                    continue;
                };
                let gamertag = decode_utf16(&gamertag_bytes);
                if !gamertag.is_empty() {
                    players.entry(xuid).or_insert(gamertag);
                }
            }
        }
    }
    players
        .into_iter()
        .map(|(xuid, gamertag)| FilmPlayer { xuid, gamertag })
        .collect()
}

/// Decodes summary events using the layout for `film_major_version`.
///
/// Major versions 39, 40, and 41 carry a 12-byte record prefix before the
/// gamertag. Other known versions start the record at the gamertag itself.
pub fn decode_events(
    chunks: &[FilmChunkData],
    players: &[FilmPlayer],
    film_major_version: i32,
) -> Vec<FilmEvent> {
    const VERSION_39_TO_41_PREFIX_BYTES: usize = 12;
    const EVENT_GAMERTAG_BYTES: usize = 32;
    const EVENT_TAIL_BYTES: usize = 60;
    const PREFIX_PADDING_BYTES: usize = 3;
    let event_prefix_bytes = match film_major_version {
        39..=41 => VERSION_39_TO_41_PREFIX_BYTES,
        _ => 0,
    };

    let mut events = Vec::new();
    for chunk in chunks.iter().filter(|chunk| chunk.metadata.chunk_type == 3) {
        for player in players {
            let Some(gamertag_field) = padded_gamertag_field(&player.gamertag) else {
                continue;
            };
            for gamertag_position in find_bit_pattern(&chunk.data, &gamertag_field) {
                let Some(event_position) = gamertag_position.checked_sub(event_prefix_bytes * 8)
                else {
                    continue;
                };
                let Some(prefix_position) = event_position.checked_sub(PREFIX_PADDING_BYTES * 8)
                else {
                    continue;
                };
                if !bits_are_zero(&chunk.data, prefix_position, PREFIX_PADDING_BYTES * 8) {
                    continue;
                }
                let Some(data) = extract_bits(&chunk.data, gamertag_position, EVENT_TAIL_BYTES * 8)
                else {
                    continue;
                };
                if data[..EVENT_GAMERTAG_BYTES] != gamertag_field {
                    continue;
                }
                events.push(FilmEvent {
                    xuid: player.xuid,
                    gamertag: player.gamertag.clone(),
                    timestamp_ms: u32::from_be_bytes(data[48..52].try_into().unwrap()),
                    kind: FilmEventKind::from_fields(data[47], data[55]),
                    medal_flag: data[55],
                    metadata: data[59],
                });
            }
        }
    }
    events.sort_by_key(|event| event.timestamp_ms);
    events.dedup();
    events
}

/// Compares decoded film event totals with the human-player counts in match stats.
///
/// Medal identity cannot be compared here because film summary medal codes and
/// the stats API's `NameId` values use different namespaces. Medal totals are
/// nevertheless useful for detecting a truncated or incorrectly decoded film.
pub fn validate_events(
    events: &[FilmEvent],
    players: &[FilmPlayer],
    match_stats: &MatchStats,
) -> FilmEventValidation {
    let mut decoded = BTreeMap::<u64, FilmEventCounts>::new();
    for event in events {
        let counts = decoded.entry(event.xuid).or_default();
        match event.kind {
            FilmEventKind::Kill => counts.kills += 1,
            FilmEventKind::Death => counts.deaths += 1,
            FilmEventKind::Medal => counts.medals += 1,
            FilmEventKind::Mode | FilmEventKind::Other(_) => {}
        }
    }

    let mut expected = BTreeMap::<u64, FilmEventCounts>::new();
    for player in match_stats
        .players
        .iter()
        .filter(|player| player.is_human())
    {
        let Some(xuid) = player_xuid(&player.player_id) else {
            continue;
        };
        let counts = expected.entry(xuid).or_default();
        for team in &player.team_stats {
            counts.kills += nonnegative_count(team.stats.core.kills);
            counts.deaths += nonnegative_count(team.stats.core.deaths);
            counts.medals += team
                .stats
                .core
                .medals
                .iter()
                .map(|medal| nonnegative_count(medal.count))
                .sum::<usize>();
        }
    }

    let mut gamertags = players
        .iter()
        .map(|player| (player.xuid, player.gamertag.clone()))
        .collect::<BTreeMap<_, _>>();
    for event in events {
        gamertags
            .entry(event.xuid)
            .or_insert_with(|| event.gamertag.clone());
    }
    let xuids = decoded
        .keys()
        .chain(expected.keys())
        .chain(gamertags.keys())
        .copied()
        .collect::<BTreeSet<_>>();

    FilmEventValidation {
        players: xuids
            .into_iter()
            .map(|xuid| FilmPlayerEventValidation {
                xuid,
                gamertag: gamertags.remove(&xuid),
                decoded: decoded.remove(&xuid).unwrap_or_default(),
                match_stats: expected.remove(&xuid).unwrap_or_default(),
            })
            .collect(),
    }
}

fn player_xuid(player_id: &str) -> Option<u64> {
    player_id
        .strip_prefix("xuid(")?
        .strip_suffix(')')?
        .parse()
        .ok()
}

fn nonnegative_count(value: i64) -> usize {
    usize::try_from(value).unwrap_or_default()
}

fn padded_gamertag_field(gamertag: &str) -> Option<[u8; 32]> {
    let encoded = gamertag
        .encode_utf16()
        .flat_map(u16::to_le_bytes)
        .collect::<Vec<_>>();
    let mut field = [0; 32];
    field.get_mut(..encoded.len())?.copy_from_slice(&encoded);
    Some(field)
}

fn decode_utf16(bytes: &[u8]) -> String {
    let values = bytes
        .chunks_exact(2)
        .map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
        .collect::<Vec<_>>();
    String::from_utf16_lossy(&values)
        .trim_matches('\0')
        .trim()
        .to_string()
}

fn bits_are_zero(data: &[u8], position: usize, length: usize) -> bool {
    extract_bits(data, position, length).is_some_and(|bytes| bytes.iter().all(|byte| *byte == 0))
}

fn find_bit_pattern(data: &[u8], pattern: &[u8]) -> Vec<usize> {
    if pattern.is_empty() || pattern.len() > data.len() {
        return Vec::new();
    }
    let end = data.len() * 8 - pattern.len() * 8;
    (0..=end)
        .filter(|position| bit_pattern_matches(data, pattern, *position))
        .collect()
}

fn bit_pattern_matches(data: &[u8], pattern: &[u8], position: usize) -> bool {
    let byte_offset = position / 8;
    let shift = position % 8;
    pattern.iter().enumerate().all(|(index, expected)| {
        let mut actual = data[byte_offset + index] << shift;
        if shift > 0 && byte_offset + index + 1 < data.len() {
            actual |= data[byte_offset + index + 1] >> (8 - shift);
        }
        actual == *expected
    })
}

fn extract_bits(data: &[u8], position: usize, length: usize) -> Option<Vec<u8>> {
    if length == 0 || position.checked_add(length)? > data.len() * 8 {
        return None;
    }
    let byte_count = length.div_ceil(8);
    let byte_offset = position / 8;
    let shift = position % 8;
    let mut output = Vec::with_capacity(byte_count);
    for index in 0..byte_count {
        let mut byte = data[byte_offset + index] << shift;
        if shift > 0 && byte_offset + index + 1 < data.len() {
            byte |= data[byte_offset + index + 1] >> (8 - shift);
        }
        output.push(byte);
    }
    Some(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::clients::hi::models::FilmChunk;

    #[test]
    fn finds_unaligned_patterns() {
        let data = [0b1011_0011, 0b0101_1110];
        assert_eq!(find_bit_pattern(&data, &[0b1100_1101]), vec![2]);
    }

    #[test]
    fn reads_msb_first_bits() {
        let mut reader = FilmBitReader::new(&[0b1011_0010, 0b0110_0000]);
        assert_eq!(reader.read(3), Some(0b101));
        assert_eq!(reader.read(7), Some(0b1001001));
        assert_eq!(reader.position(), 10);
    }

    #[test]
    fn parses_registry_slots() {
        let mut data = vec![0; REGISTRY_BLOCK_SIZE];
        let name = b"example-component";
        data[8..8 + name.len()].copy_from_slice(name);
        let chunks = [FilmChunkData {
            metadata: FilmChunk {
                index: 0,
                start_time_offset_ms: 0,
                duration_ms: 0,
                size: data.len() as i64,
                file_relative_path: String::new(),
                chunk_type: 1,
            },
            data,
        }];
        let registry = decode_registry(&chunks).unwrap();
        assert_eq!(
            registry.archetypes[0].components,
            [String::from_utf8_lossy(name)]
        );
    }

    #[test]
    fn decodes_only_complete_summary_event_envelopes() {
        let mut data = vec![0; 3];
        let mut event = [0u8; 72];
        event[..12].fill(0xa5);
        event[12..44].copy_from_slice(&padded_gamertag_field("MsNuzzles").unwrap());
        event[59] = 50;
        event[60..64].copy_from_slice(&12_345u32.to_be_bytes());
        event[71] = 42;
        data.extend_from_slice(&event);
        let chunks = [FilmChunkData {
            metadata: FilmChunk {
                index: 0,
                start_time_offset_ms: 0,
                duration_ms: 0,
                size: data.len() as i64,
                file_relative_path: String::new(),
                chunk_type: 3,
            },
            data,
        }];
        let players = [
            FilmPlayer {
                xuid: 1,
                gamertag: "Nuzzles".into(),
            },
            FilmPlayer {
                xuid: 2,
                gamertag: "MsNuzzles".into(),
            },
        ];

        assert_eq!(
            decode_events(&chunks, &players, 39),
            [FilmEvent {
                xuid: 2,
                gamertag: "MsNuzzles".into(),
                timestamp_ms: 12_345,
                kind: FilmEventKind::Kill,
                medal_flag: 0,
                metadata: 42,
            }]
        );
    }

    #[test]
    fn maps_article_medal_ids() {
        assert_eq!(
            FilmMedal::from_id(166),
            FilmMedal::Known {
                id: 166,
                name: "Mounted"
            }
        );
        assert_eq!(FilmMedal::from_id(255), FilmMedal::Unknown(255));
    }

    /// Speculative coverage for the zero-prefix fallback branch. No real film has confirmed a
    /// gamertag-first layout yet — versions 39, 40, and 41 all use the 12-byte prefix — so this
    /// exercises the fallback with a version number outside every confirmed case, not a verified
    /// real layout. Update or remove once/if a real version is found needing zero prefix bytes.
    #[test]
    fn decodes_gamertag_first_summary_event_layouts_for_unconfirmed_versions() {
        let mut data = vec![0; 3];
        let mut event = [0u8; 60];
        event[..32].copy_from_slice(&padded_gamertag_field("Nuzzles").unwrap());
        event[47] = 20;
        event[48..52].copy_from_slice(&42_000u32.to_be_bytes());
        data.extend_from_slice(&event);
        let chunks = [FilmChunkData {
            metadata: FilmChunk {
                index: 0,
                start_time_offset_ms: 0,
                duration_ms: 0,
                size: data.len() as i64,
                file_relative_path: String::new(),
                chunk_type: 3,
            },
            data,
        }];
        let players = [FilmPlayer {
            xuid: 1,
            gamertag: "Nuzzles".into(),
        }];

        let events = decode_events(&chunks, &players, 999);
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].kind, FilmEventKind::Death);
        assert_eq!(events[0].timestamp_ms, 42_000);
        assert!(decode_events(&chunks, &players, 41).is_empty());
    }

    #[test]
    fn decodes_both_player_marker_variants() {
        let mut data = Vec::new();
        for (xuid, gamertag, marker) in [
            (1u64, "Nuzzles", [0x2d, 0xc0]),
            (2u64, "MsNuzzles", [0x25, 0xc0]),
        ] {
            data.extend_from_slice(&padded_gamertag_field(gamertag).unwrap());
            data.extend_from_slice(&[0; 21]);
            data.extend_from_slice(&xuid.to_le_bytes());
            data.extend_from_slice(&marker);
        }
        let chunks = [FilmChunkData {
            metadata: FilmChunk {
                index: 0,
                start_time_offset_ms: 0,
                duration_ms: 0,
                size: data.len() as i64,
                file_relative_path: String::new(),
                chunk_type: 2,
            },
            data,
        }];

        assert_eq!(
            decode_players(&chunks),
            [
                FilmPlayer {
                    xuid: 1,
                    gamertag: "Nuzzles".into(),
                },
                FilmPlayer {
                    xuid: 2,
                    gamertag: "MsNuzzles".into(),
                },
            ]
        );
        assert_eq!(decode_diagnostics(&chunks).player_markers, 2);
    }

    #[test]
    fn validates_summary_counts_against_human_match_stats() {
        let match_stats: MatchStats = serde_json::from_value(serde_json::json!({
            "MatchId": "match",
            "MatchInfo": {
                "StartTime": "2026-01-01T00:00:00Z",
                "EndTime": "2026-01-01T00:10:00Z",
                "Duration": "PT10M",
                "GameVariantCategory": 6,
                "MapVariant": null,
                "UgcGameVariant": null,
                "Playlist": null
            },
            "Teams": [],
            "Players": [
                {
                    "PlayerId": "xuid(1)",
                    "PlayerType": 1,
                    "LastTeamId": 0,
                    "Outcome": 2,
                    "Rank": 1,
                    "PlayerTeamStats": [{
                        "TeamId": 0,
                        "Stats": { "CoreStats": {
                            "Kills": 1, "Deaths": 1,
                            "Medals": [{ "NameId": 1, "Count": 1 }]
                        }}
                    }]
                },
                {
                    "PlayerId": "xuid(2)",
                    "PlayerType": 1,
                    "LastTeamId": 0,
                    "Outcome": 2,
                    "Rank": 1,
                    "PlayerTeamStats": [{
                        "TeamId": 0,
                        "Stats": { "CoreStats": { "Kills": 1 } }
                    }]
                },
                {
                    "PlayerId": "xuid(3)",
                    "PlayerType": 2,
                    "LastTeamId": 0,
                    "Outcome": 2,
                    "Rank": 1,
                    "PlayerTeamStats": []
                }
            ]
        }))
        .unwrap();
        let players = [FilmPlayer {
            xuid: 1,
            gamertag: "Nuzzles".into(),
        }];
        let events = [
            FilmEvent {
                xuid: 1,
                gamertag: "Nuzzles".into(),
                timestamp_ms: 1,
                kind: FilmEventKind::Kill,
                medal_flag: 0,
                metadata: 0,
            },
            FilmEvent {
                xuid: 1,
                gamertag: "Nuzzles".into(),
                timestamp_ms: 2,
                kind: FilmEventKind::Death,
                medal_flag: 0,
                metadata: 0,
            },
            FilmEvent {
                xuid: 1,
                gamertag: "Nuzzles".into(),
                timestamp_ms: 3,
                kind: FilmEventKind::Medal,
                medal_flag: 1,
                metadata: 0,
            },
        ];

        let validation = validate_events(&events, &players, &match_stats);
        assert_eq!(validation.players.len(), 2);
        assert!(validation.players[0].matches_stats());
        assert!(!validation.players[1].matches_stats());
        assert!(!validation.matches_stats());
    }

    #[test]
    fn decodes_prefix_coded_record_headers() {
        assert_eq!(
            decode_frame_record_header(&[0]),
            Some(FilmRecordHeader {
                kind: FilmRecordKind::End,
                full_id: None,
                slot: None,
                header_bits: 3,
            })
        );
        let header =
            decode_frame_record_header_with_id_width(&[0b1010_1010, 0b1010_1010], 13).unwrap();
        assert_eq!(header.kind, FilmRecordKind::Delta);
        assert_eq!(header.slot, Some(0b0_1010_1010_1010));
        assert_eq!(header.header_bits, 16);
    }

    #[test]
    fn decodes_sparse_component_mask() {
        // DELTA, slot 0, tag 0, sparse mask with indices 0 and 11.
        let bits = "1 00000000000 00 0 010 000000 001011"
            .chars()
            .filter(|character| *character != ' ')
            .collect::<String>();
        let mut data = vec![0u8; bits.len().div_ceil(8)];
        for (index, character) in bits.bytes().enumerate() {
            if character == b'1' {
                data[index / 8] |= 1 << (7 - index % 8);
            }
        }
        let delta = decode_first_delta_header(&data).unwrap();
        assert_eq!(delta.record.slot, Some(0));
        assert_eq!(delta.component_mask, 1 | (1 << 11));
        assert_eq!(delta.data_bit_offset, bits.len());
    }

    #[test]
    fn decodes_dense_component_mask_component_zero_first() {
        // DELTA, slot 0, tag 0, dense mask with components 0 and 63 set.
        let bits = format!("1{:011b}0011{}1", 0, "0".repeat(62))
            .chars()
            .collect::<Vec<_>>();
        let mut data = vec![0u8; bits.len().div_ceil(8)];
        for (index, bit) in bits.into_iter().enumerate() {
            if bit == '1' {
                data[index / 8] |= 1 << (7 - index % 8);
            }
        }
        let delta = decode_first_delta_header(&data).unwrap();
        assert_eq!(delta.component_mask, 1 | (1 << 63));
    }
}