rcsa 0.2.1

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
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
//! 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: 256-wide with AVX2, 128-wide with SSE2 or NEON, 64-wide `u64`
//! words elsewhere. Only the 184-byte payloads are rewritten; TS headers are left
//! untouched.

use crate::bs::{
    block::{
        Encypher,
        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.
    ///
    /// Runs on the widest backend of the CPU whatever the batch size:
    /// - AVX2 (256 lanes) when the CPU has it, else SSE2 (128 lanes) on x86-64
    /// - NEON (128 lanes) on aarch64
    /// - `u64` (64 lanes) elsewhere.
    ///
    /// In a partial group only the block cipher shrinks to the lanes in use; the stream cipher
    /// runs the full width, so every group has a fixed cost: about a quarter of a full group
    /// on AVX2, more on the narrower backends.
    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")]
        if crate::bs::avx2::available() {
            // SAFETY: guarded by runtime AVX2 detection.
            unsafe { self.descramble_avx2(packets, blocks) }
        } else {
            // SAFETY: SSE2 is guaranteed present on every x86-64 target.
            unsafe { self.descramble_sse2(packets, blocks) }
        }
        #[cfg(target_arch = "aarch64")]
        self.descramble::<crate::bs::neon::W128>(packets, blocks);
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        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.
    ///
    /// Runs on the widest backend of the CPU whatever the batch size:
    /// - AVX2 (256 lanes) when the CPU has it, else SSE2 (128 lanes) on x86-64
    /// - NEON (128 lanes) on aarch64
    /// - `u64` (64 lanes) elsewhere.
    ///
    /// In a partial group only the block cipher shrinks to the lanes in use; the stream cipher
    /// runs the full width, so every group has a fixed cost: about a quarter of a full group
    /// on AVX2, more on the narrower backends.
    pub fn encrypt_in_place(&self, packets: &mut [u8]) {
        assert!(
            packets.len() % PKT == 0,
            "buffer length must be a multiple of 188"
        );
        self.encrypt_dispatch(packets, None);
    }

    /// Scramble 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 encrypt_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.encrypt_dispatch(packets, None);
        } else {
            self.encrypt_dispatch(packets, Some(blocks));
        }
    }

    fn encrypt_dispatch(&self, packets: &mut [u8], blocks: Option<&[u8]>) {
        #[cfg(target_arch = "x86_64")]
        if crate::bs::avx2::available() {
            // SAFETY: guarded by runtime AVX2 detection.
            unsafe { self.scramble_avx2(packets, blocks) }
        } else {
            // SAFETY: SSE2 is guaranteed present on every x86-64 target.
            unsafe { self.scramble_sse2(packets, blocks) }
        }
        #[cfg(target_arch = "aarch64")]
        self.scramble::<crate::bs::neon::W128>(packets, blocks);
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
        self.scramble::<u64>(packets, blocks);
    }

    /// 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, None);
    }

    /// 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, 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 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, None);
        }
    }

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

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

    // `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], 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]);
            scramble_group::<W>(&self.kk, &ccw, group, lanes, group_blocks);
            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, lanes); // 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, lanes);
    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,
    blocks: Option<&[u8]>,
) {
    // 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. A lane whose payload ends early starts its chain at its last whole block: the
    //    blocks after it go through the cipher as garbage and are not chained in.
    let mut ib = [[[0u8; MAX_LANES]; 8]; BLOCKS];
    let mut e = Encypher::new();
    block_encypher::<W>(&mut e, &p[22], kk, &mut ib[22], lanes);
    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];
            }
        }
        if let Some(blocks) = blocks {
            for (g, &n) in blocks.iter().enumerate() {
                if n as usize == i + 1 {
                    for j in 0 .. 8 {
                        x[j][g] = p[i][j][g];
                    }
                }
            }
        }
        block_encypher::<W>(&mut e, &x, kk, &mut ib[i], lanes);
    }

    // The partial block after a short lane's last whole one is plaintext XOR keystream only.
    if let Some(blocks) = blocks {
        for (g, &n) in blocks.iter().enumerate() {
            let n = n as usize;
            if n < BLOCKS {
                for j in 0 .. 8 {
                    ib[n][j][g] = p[n][j][g];
                }
            }
        }
    }

    // 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,
        );
    }

    /// Every lane count of one group against the scalar oracle: full payloads both ways and
    /// payloads of mixed lengths.
    fn every_lane_count<W: Word>(
        dec: impl Fn(&CsaBatch, &mut [u8], Option<&[u8]>),
        enc: impl Fn(&CsaBatch, &mut [u8]),
    ) {
        let mut rng = Rng(W::LANES as u64);
        let cw: [u8; 8] = core::array::from_fn(|_| rng.byte());
        let batch = CsaBatch::new(&cw);
        let mut csa = Csa::default();
        csa.set_cw(&cw);

        let src: Vec<u8> = (0 .. W::LANES * PKT).map(|_| rng.byte()).collect();
        let lens: Vec<usize> = (0 .. W::LANES)
            .map(|_| 8 + (rng.next() % 177) as usize)
            .collect();
        let blocks: Vec<u8> = lens.iter().map(|&len| (len / 8) as u8).collect();
        let (mut clear, mut scrambled, mut short) = (src.clone(), src.clone(), src.clone());
        for (p, &len) in lens.iter().enumerate() {
            let at = p * PKT + HDR;
            csa.decrypt_payload(&mut clear[at .. at + 184]);
            csa.encrypt_payload(&mut scrambled[at .. at + 184]);
            csa.decrypt_payload(&mut short[at .. at + len]);
        }

        for n in 1 ..= W::LANES {
            let mut buf = src[.. n * PKT].to_vec();
            dec(&batch, &mut buf, None);
            assert!(buf == clear[.. n * PKT], "decrypt {n} lanes");

            buf.copy_from_slice(&src[.. n * PKT]);
            enc(&batch, &mut buf);
            assert!(buf == scrambled[.. n * PKT], "encrypt {n} lanes");

            buf.copy_from_slice(&src[.. n * PKT]);
            dec(&batch, &mut buf, Some(&blocks[.. n]));
            for (p, &len) in lens[.. n].iter().enumerate() {
                let r = p * PKT + HDR .. p * PKT + HDR + len;
                assert!(
                    buf[r.clone()] == short[r],
                    "{n} lanes, lane {p}, {len} bytes"
                );
            }
        }
    }

    #[test]
    fn every_lane_count_u64() {
        every_lane_count::<u64>(
            |b, buf, blocks| b.descramble::<u64>(buf, blocks),
            |b, buf| b.encrypt_in_place_u64(buf),
        );
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn every_lane_count_sse2() {
        every_lane_count::<crate::bs::sse2::W128>(
            // SAFETY: SSE2 is guaranteed present on every x86-64 target.
            |b, buf, blocks| unsafe { b.descramble_sse2(buf, blocks) },
            |b, buf| b.encrypt_in_place_sse2(buf),
        );
    }

    #[test]
    #[cfg(target_arch = "x86_64")]
    fn every_lane_count_avx2() {
        if !crate::bs::avx2::available() {
            return;
        }
        every_lane_count::<crate::bs::avx2::W256>(
            // SAFETY: guarded by runtime AVX2 detection.
            |b, buf, blocks| unsafe { b.descramble_avx2(buf, blocks) },
            |b, buf| b.encrypt_in_place_avx2(buf),
        );
    }

    #[test]
    #[cfg(target_arch = "aarch64")]
    fn every_lane_count_neon() {
        every_lane_count::<crate::bs::neon::W128>(
            |b, buf, blocks| b.descramble::<crate::bs::neon::W128>(buf, blocks),
            |b, buf| b.scramble::<crate::bs::neon::W128>(buf),
        );
    }

    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, full and partial 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, full and partial 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, in partial and full groups.
    #[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}");
            }
        }
    }

    /// `encrypt_payloads_in_place` matches the scalar `encrypt_payload` for every payload
    /// length, mixed in one batch, in partial and full groups.
    #[test]
    fn encrypt_payloads_vs_scalar() {
        let mut rng = Rng(11);
        for n in [1usize, 63, 64, 130, 300, 700] {
            let cw: [u8; 8] = core::array::from_fn(|_| rng.byte());
            // every length 8 ..= 184 shows up in the larger batches
            let lens: Vec<usize> = (0 .. n)
                .map(|p| {
                    if n >= 300 {
                        8 + p % 177
                    } else {
                        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.encrypt_payload(&mut slot[HDR .. HDR + len]);
            }

            let blocks: Vec<u8> = lens.iter().map(|&len| (len / 8) as u8).collect();
            let batch = CsaBatch::new(&cw);
            let mut wide = buf.clone();
            batch.encrypt_payloads_in_place(&mut wide, &blocks);
            let mut narrow = buf.clone();
            batch.scramble::<u64>(&mut narrow, Some(&blocks));
            #[cfg(target_arch = "x86_64")]
            // SAFETY: SSE2 is guaranteed present on every x86-64 target.
            unsafe {
                batch.scramble_sse2(&mut buf, Some(&blocks));
            }
            #[cfg(not(target_arch = "x86_64"))]
            buf.copy_from_slice(&narrow);
            for (p, &len) in lens.iter().enumerate() {
                let r = p * PKT + HDR .. p * PKT + HDR + len;
                assert_eq!(
                    wide[r.clone()],
                    expected[r.clone()],
                    "n {n} lane {p} len {len}"
                );
                assert_eq!(
                    narrow[r.clone()],
                    expected[r.clone()],
                    "u64 n {n} lane {p} len {len}"
                );
                assert_eq!(buf[r.clone()], expected[r], "sse2 n {n} lane {p} len {len}");
            }
        }
    }
}