rcsa 0.2.0

DVB Common Scrambling Algorithm (CSA) descrambler and scrambler for MPEG-TS
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
//! Public batch API: in-place, bitsliced descrambling of many TS packets.
//!
//! [`CsaBatch`] holds the expanded key and descrambles a contiguous buffer of
//! concatenated 188-byte packets in place, processing `Word::LANES` packets per
//! machine word. On x86-64 with AVX2 it uses 256-wide words; otherwise 64-wide
//! `u64` words. Only the 184-byte payloads are rewritten; TS headers are left
//! untouched.

use crate::bs::{
    block::{
        block_decypher,
        block_encypher,
    },
    nibble::Nibble,
    stream::StreamState,
    word::{
        BLOCKS,
        MAX_LANES,
        PKT,
        Word,
        load_block,
        load_block_bytes,
        store_block_bytes,
    },
};

/// Batch DVB-CSA descrambler for a fixed control word.
pub struct CsaBatch {
    cw: [u8; 8],
    kk: [u8; 56],
}

impl CsaBatch {
    /// Create a descrambler for control word `cw`.
    pub fn new(cw: &[u8; 8]) -> Self {
        let mut s = CsaBatch {
            cw: [0; 8],
            kk: [0; 56],
        };
        s.set_cw(cw);
        s
    }

    /// Re-key with a new control word (same schedule as the scalar `Csa`).
    pub fn set_cw(&mut self, cw: &[u8; 8]) {
        self.cw = *cw;
        crate::key::expand_key(&mut self.kk, cw);
    }

    /// Descramble a contiguous buffer of concatenated 188-byte TS packets in
    /// place. `packets.len()` must be a multiple of 188.
    ///
    /// Picks the widest backend the batch actually *fills*:
    /// - AVX2 (256 lanes) for ≥256 packets when the CPU has it
    /// - SSE2 (128 lanes, x86-64 baseline) for ≥128 packets
    /// - NEON (128 lanes) for ≥128 packets on aarch64
    /// - `u64` (64 lanes) otherwise.
    pub fn decrypt_in_place(&self, packets: &mut [u8]) {
        assert!(
            packets.len() % PKT == 0,
            "buffer length must be a multiple of 188"
        );
        self.decrypt_dispatch(packets, None);
    }

    /// Descramble payloads of any length in place: `packets` holds 188-byte slots, each with
    /// its payload at byte 4, and `blocks[i]` is the count of whole 8-byte blocks in slot
    /// `i`'s payload (1 ..= 23). Bytes after a payload's trailing partial block are
    /// overwritten.
    pub(crate) fn decrypt_payloads_in_place(&self, packets: &mut [u8], blocks: &[u8]) {
        assert!(
            packets.len() == blocks.len() * PKT,
            "one block count per 188-byte slot"
        );
        debug_assert!(blocks.iter().all(|&n| (1 ..= BLOCKS as u8).contains(&n)));
        if blocks.iter().all(|&n| n == BLOCKS as u8) {
            self.decrypt_dispatch(packets, None);
        } else {
            self.decrypt_dispatch(packets, Some(blocks));
        }
    }

    fn decrypt_dispatch(&self, packets: &mut [u8], blocks: Option<&[u8]>) {
        #[cfg(target_arch = "x86_64")]
        {
            let n = packets.len() / PKT;
            if n >= <crate::bs::avx2::W256 as Word>::LANES && crate::bs::avx2::available() {
                // SAFETY: guarded by runtime AVX2 detection.
                unsafe {
                    self.descramble_avx2(packets, blocks);
                }
                return;
            }
            if n >= <crate::bs::sse2::W128 as Word>::LANES {
                // SAFETY: SSE2 is guaranteed present on every x86-64 target.
                unsafe {
                    self.descramble_sse2(packets, blocks);
                }
                return;
            }
        }
        #[cfg(target_arch = "aarch64")]
        if packets.len() / PKT >= <crate::bs::neon::W128 as Word>::LANES {
            self.descramble::<crate::bs::neon::W128>(packets, blocks);
            return;
        }
        self.descramble::<u64>(packets, blocks);
    }

    /// Force the portable 64-wide backend (mainly for benchmarks/tests).
    #[doc(hidden)]
    pub fn decrypt_in_place_u64(&self, packets: &mut [u8]) {
        assert!(
            packets.len() % PKT == 0,
            "buffer length must be a multiple of 188"
        );
        self.descramble::<u64>(packets, None);
    }

    /// Force the AVX2 256-wide backend. Panics if AVX2 is unavailable.
    #[doc(hidden)]
    #[cfg(target_arch = "x86_64")]
    pub fn decrypt_in_place_avx2(&self, packets: &mut [u8]) {
        assert!(
            packets.len() % PKT == 0,
            "buffer length must be a multiple of 188"
        );
        assert!(crate::bs::avx2::available(), "AVX2 not available");
        // SAFETY: asserted above.
        unsafe {
            self.descramble_avx2(packets, None);
        }
    }

    /// Force the SSE2 128-wide backend. SSE2 is baseline on x86-64, so this is
    /// always available; it is the natural fallback when AVX2 is absent.
    #[doc(hidden)]
    #[cfg(target_arch = "x86_64")]
    pub fn decrypt_in_place_sse2(&self, packets: &mut [u8]) {
        assert!(
            packets.len() % PKT == 0,
            "buffer length must be a multiple of 188"
        );
        // SAFETY: SSE2 is guaranteed present on every x86-64 target.
        unsafe {
            self.descramble_sse2(packets, None);
        }
    }

    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "avx2")]
    unsafe fn descramble_avx2(&self, packets: &mut [u8], blocks: Option<&[u8]>) {
        self.descramble::<crate::bs::avx2::W256>(packets, blocks);
    }

    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "sse2")]
    unsafe fn descramble_sse2(&self, packets: &mut [u8], blocks: Option<&[u8]>) {
        self.descramble::<crate::bs::sse2::W128>(packets, blocks);
    }

    // `inline(always)` throughout the W256 chain so it collapses into the
    // `descramble_avx2` `#[target_feature]` root and the SIMD ops fuse to AVX2.
    #[inline(always)]
    fn descramble<W: Word>(&self, packets: &mut [u8], blocks: Option<&[u8]>) {
        let ccw = ccw_bits::<W>(&self.cw);
        let total = packets.len() / PKT;
        let mut done = 0;
        while done < total {
            let lanes = core::cmp::min(W::LANES, total - done);
            let group = &mut packets[done * PKT .. (done + lanes) * PKT];
            let group_blocks = blocks.map(|b| &b[done .. done + lanes]);
            descramble_group::<W>(&self.kk, &ccw, group, lanes, group_blocks);
            done += lanes;
        }
    }

    /// Scramble a contiguous buffer of concatenated 188-byte TS packets in
    /// place. `packets.len()` must be a multiple of 188.
    ///
    /// Picks the widest backend the batch actually *fills*:
    /// - AVX2 (256 lanes) for ≥256 packets when the CPU has it
    /// - SSE2 (128 lanes, x86-64 baseline) for ≥128 packets
    /// - NEON (128 lanes) for ≥128 packets on aarch64
    /// - `u64` (64 lanes) otherwise.
    pub fn encrypt_in_place(&self, packets: &mut [u8]) {
        assert!(
            packets.len() % PKT == 0,
            "buffer length must be a multiple of 188"
        );
        #[cfg(target_arch = "x86_64")]
        {
            let n = packets.len() / PKT;
            if n >= <crate::bs::avx2::W256 as Word>::LANES && crate::bs::avx2::available() {
                // SAFETY: guarded by runtime AVX2 detection.
                unsafe {
                    self.scramble_avx2(packets);
                }
                return;
            }
            if n >= <crate::bs::sse2::W128 as Word>::LANES {
                // SAFETY: SSE2 is guaranteed present on every x86-64 target.
                unsafe {
                    self.scramble_sse2(packets);
                }
                return;
            }
        }
        #[cfg(target_arch = "aarch64")]
        if packets.len() / PKT >= <crate::bs::neon::W128 as Word>::LANES {
            self.scramble::<crate::bs::neon::W128>(packets);
            return;
        }
        self.scramble::<u64>(packets);
    }

    /// Force the portable 64-wide backend (mainly for benchmarks/tests).
    #[doc(hidden)]
    pub fn encrypt_in_place_u64(&self, packets: &mut [u8]) {
        assert!(
            packets.len() % PKT == 0,
            "buffer length must be a multiple of 188"
        );
        self.scramble::<u64>(packets);
    }

    /// Force the AVX2 256-wide backend. Panics if AVX2 is unavailable.
    #[doc(hidden)]
    #[cfg(target_arch = "x86_64")]
    pub fn encrypt_in_place_avx2(&self, packets: &mut [u8]) {
        assert!(
            packets.len() % PKT == 0,
            "buffer length must be a multiple of 188"
        );
        assert!(crate::bs::avx2::available(), "AVX2 not available");
        // SAFETY: asserted above.
        unsafe {
            self.scramble_avx2(packets);
        }
    }

    /// Force the SSE2 128-wide backend. SSE2 is baseline on x86-64, so this is
    /// always available; it is the natural fallback when AVX2 is absent.
    #[doc(hidden)]
    #[cfg(target_arch = "x86_64")]
    pub fn encrypt_in_place_sse2(&self, packets: &mut [u8]) {
        assert!(
            packets.len() % PKT == 0,
            "buffer length must be a multiple of 188"
        );
        // SAFETY: SSE2 is guaranteed present on every x86-64 target.
        unsafe {
            self.scramble_sse2(packets);
        }
    }

    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "avx2")]
    unsafe fn scramble_avx2(&self, packets: &mut [u8]) {
        self.scramble::<crate::bs::avx2::W256>(packets);
    }

    #[cfg(target_arch = "x86_64")]
    #[target_feature(enable = "sse2")]
    unsafe fn scramble_sse2(&self, packets: &mut [u8]) {
        self.scramble::<crate::bs::sse2::W128>(packets);
    }

    // `inline(always)` throughout the W256 chain so it collapses into the
    // `scramble_avx2` `#[target_feature]` root and the SIMD ops fuse to AVX2.
    #[inline(always)]
    fn scramble<W: Word>(&self, packets: &mut [u8]) {
        let ccw = ccw_bits::<W>(&self.cw);
        let total = packets.len() / PKT;
        let mut done = 0;
        while done < total {
            let lanes = core::cmp::min(W::LANES, total - done);
            let group = &mut packets[done * PKT .. (done + lanes) * PKT];
            scramble_group::<W>(&self.kk, &ccw, group, lanes);
            done += lanes;
        }
    }
}

/// Broadcast the 16 CW nibbles, matching `Csa::set_cw`: `ccw[2i]` = high nibble
/// of `cw[i]` (bits 4..8), `ccw[2i+1]` = low nibble (bits 0..4), LSB-first.
#[inline(always)]
fn ccw_bits<W: Word>(cw: &[u8; 8]) -> [Nibble<W>; 16] {
    let mut ccw = [Nibble::zero(); 16];
    for i in 0 .. 8 {
        let hi = cw[i] >> 4;
        ccw[2 * i] = Nibble(
            W::splat(hi & 1 == 1),
            W::splat((hi >> 1) & 1 == 1),
            W::splat((hi >> 2) & 1 == 1),
            W::splat((hi >> 3) & 1 == 1),
        );
        let lo = cw[i];
        ccw[2 * i + 1] = Nibble(
            W::splat(lo & 1 == 1),
            W::splat((lo >> 1) & 1 == 1),
            W::splat((lo >> 2) & 1 == 1),
            W::splat((lo >> 3) & 1 == 1),
        );
    }
    ccw
}

/// Descramble up to `W::LANES` packets (`lanes` valid) in place.
#[inline(always)]
fn descramble_group<W: Word>(
    kk: &[u8; 56],
    ccw: &[Nibble<W>; 16],
    group: &mut [u8],
    lanes: usize,
    blocks: Option<&[u8]>,
) {
    // 1. Preload all 23 ciphertext blocks in BYTE domain (cheap strided gather), so writing
    //    plaintext back can never clobber ciphertext still needed.
    let mut ct = [[[0u8; MAX_LANES]; 8]; BLOCKS];
    for k in 0 .. BLOCKS {
        load_block_bytes(group, lanes, k, &mut ct[k]);
    }

    // 2. Byte-domain block-cipher state; zero-init once (T is fully rebuilt each block -- same
    //    invariant as the bitsliced path).
    let mut t = [[0u8; MAX_LANES]; 64];

    // 3. Stream cipher stays bitsliced; its seed needs block 0 in bitslice form.
    let seed = load_block::<W>(group, lanes, 0);
    let mut st = StreamState::<W>::new();
    st.stream_init(ccw);
    st.stream_cypher_init(&seed);

    // 4. Running block-cipher input (byte domain); starts as ciphertext block 0.
    let mut block = ct[0];
    let mut ks_bytes = [[0u8; MAX_LANES]; 8];
    let mut pt = [[0u8; MAX_LANES]; 8];
    // Keystream-only plaintext of a short lane's trailing partial block.
    let mut tail = [[0u8; MAX_LANES]; 8];

    for i in 0 .. 22 {
        block_decypher::<W>(&mut t, &block, kk); // t[0..8] = byte-domain output
        let ks = st.stream_cypher(); // bitsliced Block<W>
        for j in 0 .. 8 {
            W::scatter_bitplanes(&ks[j], &mut ks_bytes[j][.. W::LANES]); // bit -> byte
        }
        for j in 0 .. 8 {
            for g in 0 .. lanes {
                let nb = ks_bytes[j][g] ^ ct[i + 1][j][g];
                block[j][g] = nb; // next cipher input
                pt[j][g] = nb ^ t[j][g]; // plaintext
            }
        }
        if let Some(blocks) = blocks {
            short_lanes(blocks, i, &block, &t, &mut pt, &mut tail);
        }
        store_block_bytes(&pt, group, lanes, i);
    }

    // Last block: plaintext is t[0..8] directly (no keystream/ciphertext combine).
    block_decypher::<W>(&mut t, &block, kk);
    let mut last = [[0u8; MAX_LANES]; 8];
    last.copy_from_slice(&t[0 .. 8]);
    if let Some(blocks) = blocks {
        short_lanes(blocks, BLOCKS - 1, &block, &t, &mut last, &mut tail);
    }
    store_block_bytes(&last, group, lanes, BLOCKS - 1);
}

/// Fixes block `i` of the lanes whose payload ends early: the last whole block is the bare
/// block-cipher output and the partial block after it is keystream XOR ciphertext only.
/// Blocks past a lane's payload are left as garbage.
#[inline(always)]
fn short_lanes(
    blocks: &[u8],
    i: usize,
    block: &[[u8; MAX_LANES]; 8],
    t: &[[u8; MAX_LANES]; 64],
    pt: &mut [[u8; MAX_LANES]; 8],
    tail: &mut [[u8; MAX_LANES]; 8],
) {
    for (g, &n) in blocks.iter().enumerate() {
        let n = n as usize;
        if i + 1 == n {
            for j in 0 .. 8 {
                tail[j][g] = block[j][g];
                pt[j][g] = t[j][g];
            }
        } else if i == n {
            for j in 0 .. 8 {
                pt[j][g] = tail[j][g];
            }
        }
    }
}

/// Scramble up to `W::LANES` packets (`lanes` valid) in place.
#[inline(always)]
fn scramble_group<W: Word>(kk: &[u8; 56], ccw: &[Nibble<W>; 16], group: &mut [u8], lanes: usize) {
    // 1. Load all 23 plaintext blocks in BYTE domain (cheap strided gather).
    let mut p = [[[0u8; MAX_LANES]; 8]; BLOCKS];
    for k in 0 .. BLOCKS {
        load_block_bytes(group, lanes, k, &mut p[k]);
    }

    // 2. Backward block-cipher chain: IB[22] = BCinv(P[22]); IB[i] = BCinv(P[i] ^ IB[i+1]) for i =
    //    21..=0.
    let mut ib = [[[0u8; MAX_LANES]; 8]; BLOCKS];
    block_encypher::<W>(&p[22], kk, &mut ib[22]);
    let mut x = [[0u8; MAX_LANES]; 8];
    for i in (0 .. 22).rev() {
        for j in 0 .. 8 {
            for g in 0 .. lanes {
                x[j][g] = p[i][j][g] ^ ib[i + 1][j][g];
            }
        }
        block_encypher::<W>(&x, kk, &mut ib[i]);
    }

    // 3. SB[0] = IB[0]: block 0 is the stream seed, not keystream-XORed.
    store_block_bytes(&ib[0], group, lanes, 0);

    // Seed the (bitsliced) stream cipher from SB[0] = IB[0], same as decrypt
    // seeds from SB[0] (byte planes -> bitslice form).
    let mut seed = [[W::zero(); 8]; 8];
    for j in 0 .. 8 {
        seed[j] = W::gather_bitplanes(&ib[0][j][0 .. lanes]);
    }
    let mut st = StreamState::<W>::new();
    st.stream_init(ccw);
    st.stream_cypher_init(&seed);

    // 4. SB[k] = IB[k] ^ KS[k-1] for k = 1..22.
    let mut ks_bytes = [[0u8; MAX_LANES]; 8];
    let mut sb = [[0u8; MAX_LANES]; 8];
    for k in 1 .. BLOCKS {
        let ks = st.stream_cypher(); // bitsliced Block<W>
        for j in 0 .. 8 {
            W::scatter_bitplanes(&ks[j], &mut ks_bytes[j][.. W::LANES]); // bit -> byte
        }
        for j in 0 .. 8 {
            for g in 0 .. lanes {
                sb[j][g] = ib[k][j][g] ^ ks_bytes[j][g];
            }
        }
        store_block_bytes(&sb, group, lanes, k);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        Csa,
        bs::word::HDR,
    };

    include!("../../fixtures/dvb_csa.rs");

    struct Rng(u64);
    impl Rng {
        fn next(&mut self) -> u64 {
            self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
            let mut z = self.0;
            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
            z ^ (z >> 31)
        }
        fn byte(&mut self) -> u8 {
            self.next() as u8
        }
    }

    /// Scalar oracle: decrypt one packet with a fresh `Csa`.
    fn scalar(cw: &[u8; 8], pkt: &[u8]) -> Vec<u8> {
        let mut c = Csa::default();
        c.set_cw(cw);
        let mut out = vec![0u8; pkt.len()];
        c.decrypt(pkt, &mut out);
        out
    }

    /// Scalar oracle: encrypt one packet with a fresh `Csa`.
    fn scalar_encrypt(cw: &[u8; 8], pkt: &[u8]) -> Vec<u8> {
        let mut c = Csa::default();
        c.set_cw(cw);
        let mut out = vec![0u8; pkt.len()];
        c.encrypt(pkt, &mut out);
        out
    }

    #[test]
    fn batch_kat_u64() {
        let n = 64;
        let mut buf = TS_SCRAMBLED.repeat(n);
        CsaBatch::new(&CW).decrypt_in_place_u64(&mut buf);
        for p in 0 .. n {
            assert_eq!(&buf[p * PKT .. (p + 1) * PKT], TS_CLEAR, "lane {p}");
        }
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn batch_kat_avx2() {
        if !crate::bs::avx2::available() {
            return;
        }
        let n = 256;
        let mut buf = TS_SCRAMBLED.repeat(n);
        CsaBatch::new(&CW).decrypt_in_place_avx2(&mut buf);
        for p in 0 .. n {
            assert_eq!(&buf[p * PKT .. (p + 1) * PKT], TS_CLEAR, "lane {p}");
        }
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn batch_kat_sse2() {
        // SSE2 is baseline on x86-64; no runtime detection needed.
        let n = 128;
        let mut buf = TS_SCRAMBLED.repeat(n);
        CsaBatch::new(&CW).decrypt_in_place_sse2(&mut buf);
        for p in 0 .. n {
            assert_eq!(&buf[p * PKT .. (p + 1) * PKT], TS_CLEAR, "lane {p}");
        }
    }

    #[test]
    fn batch_encrypt_kat_u64() {
        let n = 64;
        let mut buf = TS_CLEAR.repeat(n);
        CsaBatch::new(&CW).encrypt_in_place_u64(&mut buf);
        for p in 0 .. n {
            assert_eq!(&buf[p * PKT .. (p + 1) * PKT], TS_SCRAMBLED, "lane {p}");
        }
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn batch_encrypt_kat_avx2() {
        if !crate::bs::avx2::available() {
            return;
        }
        let n = 256;
        let mut buf = TS_CLEAR.repeat(n);
        CsaBatch::new(&CW).encrypt_in_place_avx2(&mut buf);
        for p in 0 .. n {
            assert_eq!(&buf[p * PKT .. (p + 1) * PKT], TS_SCRAMBLED, "lane {p}");
        }
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn batch_encrypt_kat_sse2() {
        // SSE2 is baseline on x86-64; no runtime detection needed.
        let n = 128;
        let mut buf = TS_CLEAR.repeat(n);
        CsaBatch::new(&CW).encrypt_in_place_sse2(&mut buf);
        for p in 0 .. n {
            assert_eq!(&buf[p * PKT .. (p + 1) * PKT], TS_SCRAMBLED, "lane {p}");
        }
    }

    /// encrypt then decrypt (and decrypt then encrypt) must return the original
    /// buffer, all 188 bytes per packet, header included.
    fn round_trip(
        encrypt: impl Fn(&CsaBatch, &mut [u8]),
        decrypt: impl Fn(&CsaBatch, &mut [u8]),
        count: usize,
        seed: u64,
    ) {
        let mut rng = Rng(seed);
        let mut cw = [0u8; 8];
        for x in cw.iter_mut() {
            *x = rng.byte();
        }
        let mut buf = vec![0u8; count * PKT];
        for x in buf.iter_mut() {
            *x = rng.byte();
        }
        let orig = buf.clone();
        let batch = CsaBatch::new(&cw);
        encrypt(&batch, &mut buf);
        decrypt(&batch, &mut buf);
        assert_eq!(buf, orig, "encrypt->decrypt not identity");
        decrypt(&batch, &mut buf);
        encrypt(&batch, &mut buf);
        assert_eq!(buf, orig, "decrypt->encrypt not identity");
    }

    #[test]
    fn round_trip_u64() {
        round_trip(
            |b, buf| b.encrypt_in_place_u64(buf),
            |b, buf| b.decrypt_in_place_u64(buf),
            100,
            0x1CE0_CEA5_u64,
        );
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn round_trip_avx2() {
        if !crate::bs::avx2::available() {
            return;
        }
        round_trip(
            |b, buf| b.encrypt_in_place_avx2(buf),
            |b, buf| b.decrypt_in_place_avx2(buf),
            300,
            0xAB5_1DE_5EED_u64,
        );
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn round_trip_sse2() {
        round_trip(
            |b, buf| b.encrypt_in_place_sse2(buf),
            |b, buf| b.decrypt_in_place_sse2(buf),
            150,
            0x5EED_C0DE_u64,
        );
    }

    fn differential(mut run: impl FnMut(&CsaBatch, &mut [u8]), iters: usize, max: usize) {
        let mut rng = Rng(0x0BAD_F00D_1234_5678);
        for _ in 0 .. iters {
            let mut cw = [0u8; 8];
            for x in cw.iter_mut() {
                *x = rng.byte();
            }
            let count = 1 + (rng.next() as usize) % max;
            let mut buf = vec![0u8; count * PKT];
            for x in buf.iter_mut() {
                *x = rng.byte();
            }
            let mut expect = buf.clone();
            for p in 0 .. count {
                let out = scalar(&cw, &buf[p * PKT .. (p + 1) * PKT]);
                expect[p * PKT .. (p + 1) * PKT].copy_from_slice(&out);
            }
            let batch = CsaBatch::new(&cw);
            run(&batch, &mut buf);
            for p in 0 .. count {
                assert_eq!(
                    &buf[p * PKT .. (p + 1) * PKT],
                    &expect[p * PKT .. (p + 1) * PKT],
                    "packet {p} of {count} diverged"
                );
            }
        }
    }

    #[test]
    fn differential_vs_scalar_u64() {
        differential(|b, buf| b.decrypt_in_place_u64(buf), 100, 200);
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn differential_vs_scalar_avx2() {
        if !crate::bs::avx2::available() {
            return;
        }
        differential(|b, buf| b.decrypt_in_place_avx2(buf), 20, 600);
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn differential_vs_scalar_sse2() {
        differential(|b, buf| b.decrypt_in_place_sse2(buf), 20, 400);
    }

    #[test]
    fn partial_batches_u64() {
        let mut rng = Rng(0xC0FF_EE00);
        let mut cw = [0u8; 8];
        for x in cw.iter_mut() {
            *x = rng.byte();
        }
        for &count in &[1usize, 3, 63, 64, 65, 127, 128, 131] {
            let mut buf = vec![0u8; count * PKT];
            for x in buf.iter_mut() {
                *x = rng.byte();
            }
            let mut expect = buf.clone();
            for p in 0 .. count {
                let out = scalar(&cw, &buf[p * PKT .. (p + 1) * PKT]);
                expect[p * PKT .. (p + 1) * PKT].copy_from_slice(&out);
            }
            CsaBatch::new(&cw).decrypt_in_place_u64(&mut buf);
            assert_eq!(buf, expect, "count {count}");
        }
    }

    /// `decrypt_in_place` must be bit-exact at every size, exercising the
    /// size-aware backend crossovers (u64 / SSE2 128 / AVX2 256) and partial
    /// trailing groups.
    #[test]
    fn dispatch_auto_all_sizes() {
        let mut rng = Rng(0xD15_9A7C_4321);
        let mut cw = [0u8; 8];
        for x in cw.iter_mut() {
            *x = rng.byte();
        }
        for &count in &[
            1usize, 63, 64, 65, 127, 128, 129, 200, 255, 256, 257, 384, 512, 700,
        ] {
            let mut buf = vec![0u8; count * PKT];
            for x in buf.iter_mut() {
                *x = rng.byte();
            }
            let mut expect = buf.clone();
            for p in 0 .. count {
                let out = scalar(&cw, &buf[p * PKT .. (p + 1) * PKT]);
                expect[p * PKT .. (p + 1) * PKT].copy_from_slice(&out);
            }
            CsaBatch::new(&cw).decrypt_in_place(&mut buf);
            assert_eq!(buf, expect, "count {count}");
        }
    }

    fn differential_encrypt(mut run: impl FnMut(&CsaBatch, &mut [u8]), iters: usize, max: usize) {
        let mut rng = Rng(0xD00D_FEED_8765_4321);
        for _ in 0 .. iters {
            let mut cw = [0u8; 8];
            for x in cw.iter_mut() {
                *x = rng.byte();
            }
            let count = 1 + (rng.next() as usize) % max;
            let mut buf = vec![0u8; count * PKT];
            for x in buf.iter_mut() {
                *x = rng.byte();
            }
            let mut expect = buf.clone();
            for p in 0 .. count {
                let out = scalar_encrypt(&cw, &buf[p * PKT .. (p + 1) * PKT]);
                expect[p * PKT .. (p + 1) * PKT].copy_from_slice(&out);
            }
            let batch = CsaBatch::new(&cw);
            run(&batch, &mut buf);
            for p in 0 .. count {
                assert_eq!(
                    &buf[p * PKT .. (p + 1) * PKT],
                    &expect[p * PKT .. (p + 1) * PKT],
                    "packet {p} of {count} diverged"
                );
            }
        }
    }

    #[test]
    fn differential_encrypt_vs_scalar_u64() {
        differential_encrypt(|b, buf| b.encrypt_in_place_u64(buf), 100, 200);
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn differential_encrypt_vs_scalar_avx2() {
        if !crate::bs::avx2::available() {
            return;
        }
        differential_encrypt(|b, buf| b.encrypt_in_place_avx2(buf), 20, 600);
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn differential_encrypt_vs_scalar_sse2() {
        differential_encrypt(|b, buf| b.encrypt_in_place_sse2(buf), 20, 400);
    }

    #[test]
    fn partial_encrypt_batches_u64() {
        let mut rng = Rng(0xFACE_B00C);
        let mut cw = [0u8; 8];
        for x in cw.iter_mut() {
            *x = rng.byte();
        }
        for &count in &[
            1usize, 3, 63, 64, 65, 127, 128, 129, 200, 255, 256, 257, 384, 512, 700,
        ] {
            let mut buf = vec![0u8; count * PKT];
            for x in buf.iter_mut() {
                *x = rng.byte();
            }
            let mut expect = buf.clone();
            for p in 0 .. count {
                let out = scalar_encrypt(&cw, &buf[p * PKT .. (p + 1) * PKT]);
                expect[p * PKT .. (p + 1) * PKT].copy_from_slice(&out);
            }
            CsaBatch::new(&cw).encrypt_in_place_u64(&mut buf);
            assert_eq!(buf, expect, "count {count}");
        }
    }

    /// `encrypt_in_place` must be bit-exact at every size, exercising the
    /// size-aware backend crossovers (u64 / SSE2 128 / AVX2 256) and partial
    /// trailing groups.
    #[test]
    fn encrypt_dispatch_auto_all_sizes() {
        let mut rng = Rng(0xE4C_1234_9A7C);
        let mut cw = [0u8; 8];
        for x in cw.iter_mut() {
            *x = rng.byte();
        }
        for &count in &[
            1usize, 3, 63, 64, 65, 127, 128, 129, 200, 255, 256, 257, 384, 512, 700,
        ] {
            let mut buf = vec![0u8; count * PKT];
            for x in buf.iter_mut() {
                *x = rng.byte();
            }
            let mut expect = buf.clone();
            for p in 0 .. count {
                let out = scalar_encrypt(&cw, &buf[p * PKT .. (p + 1) * PKT]);
                expect[p * PKT .. (p + 1) * PKT].copy_from_slice(&out);
            }
            CsaBatch::new(&cw).encrypt_in_place(&mut buf);
            assert_eq!(buf, expect, "count {count}");
        }
    }

    /// `decrypt_payloads_in_place` matches the scalar `decrypt_payload` for every payload
    /// length, mixed in one batch, at every dispatched width.
    #[test]
    fn payloads_vs_scalar() {
        let mut rng = Rng(7);
        for n in [1usize, 63, 64, 130, 300] {
            let cw: [u8; 8] = core::array::from_fn(|_| rng.byte());
            let lens: Vec<usize> = (0 .. n).map(|_| 8 + (rng.next() % 177) as usize).collect();
            let mut buf = vec![0u8; n * PKT];
            for (slot, &len) in buf.chunks_exact_mut(PKT).zip(&lens) {
                for b in &mut slot[HDR .. HDR + len] {
                    *b = rng.byte();
                }
            }

            let mut csa = Csa::default();
            csa.set_cw(&cw);
            let mut expected = buf.clone();
            for (slot, &len) in expected.chunks_exact_mut(PKT).zip(&lens) {
                csa.decrypt_payload(&mut slot[HDR .. HDR + len]);
            }

            let blocks: Vec<u8> = lens.iter().map(|&len| (len / 8) as u8).collect();
            CsaBatch::new(&cw).decrypt_payloads_in_place(&mut buf, &blocks);
            for (p, &len) in lens.iter().enumerate() {
                let r = p * PKT + HDR .. p * PKT + HDR + len;
                assert_eq!(buf[r.clone()], expected[r], "n {n} lane {p} len {len}");
            }
        }
    }
}