oxideav-opus 0.0.8

Opus audio codec for oxideav — SILK + CELT decode (mono/stereo), CELT-only full-band encode, SILK-only encode (NB/MB/WB, mono+stereo, 10/20/40/60 ms)
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
//! Opus packet framing — RFC 6716 §3.
//!
//! Every Opus packet begins with a **TOC** ("table of contents") byte that
//! describes the encoded mode, audio bandwidth, frame size, channel count and
//! framing code (how many frames are packed into this packet and how their
//! sizes are encoded).
//!
//! ```text
//!   0
//!   0 1 2 3 4 5 6 7
//!  +-+-+-+-+-+-+-+-+
//!  | config  |s| c |
//!  +-+-+-+-+-+-+-+-+
//! ```
//!
//! * `config` — 5-bit mode + bandwidth + frame-size descriptor (Table 2)
//! * `s` — stereo flag (0 = mono, 1 = stereo)
//! * `c` — framing code (0 = 1 frame, 1 = 2 equal-sized frames,
//!   2 = 2 differently-sized frames, 3 = signalled count).
//!
//! This module parses that byte, plus the remainder of the packet (the
//! per-frame length signalling when `c ∈ {1, 2, 3}`) so the downstream
//! decoder just sees a sequence of already-split frame byte slices.

use oxideav_core::{Error, Result};

/// Internal-decoder mode indicated by the TOC `config` field.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum OpusMode {
    /// Speech-oriented, LPC-based (RFC 6716 §4.2).
    SilkOnly,
    /// SILK low band + CELT high band (RFC 6716 §4).
    Hybrid,
    /// Music-oriented, MDCT-based (RFC 6716 §4.3).
    CeltOnly,
}

/// Audio bandwidth category implied by the TOC `config`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum OpusBandwidth {
    /// 4 kHz — Narrowband.
    Narrowband,
    /// 6 kHz — Mediumband (SILK-only).
    Mediumband,
    /// 8 kHz — Wideband.
    Wideband,
    /// 12 kHz — Super-wideband.
    SuperWideband,
    /// 20 kHz — Fullband.
    Fullband,
}

impl OpusBandwidth {
    /// Nominal cut-off frequency in Hz.
    pub fn cutoff_hz(self) -> u32 {
        match self {
            Self::Narrowband => 4_000,
            Self::Mediumband => 6_000,
            Self::Wideband => 8_000,
            Self::SuperWideband => 12_000,
            Self::Fullband => 20_000,
        }
    }
}

/// Decoded TOC byte.
#[derive(Copy, Clone, Debug)]
pub struct Toc {
    pub config: u8,
    pub mode: OpusMode,
    pub bandwidth: OpusBandwidth,
    /// Frame duration in 1/48000 units (audio always exits the decoder at
    /// 48 kHz). A 20-ms frame is 960 samples; a 2.5-ms frame is 120 samples.
    pub frame_samples_48k: u32,
    pub stereo: bool,
    /// Framing-code field (0..=3, RFC §3.2.1).
    pub code: u8,
}

impl Toc {
    /// Parse just the TOC byte. The `config` field is looked up against
    /// RFC 6716 Table 2 to populate `mode`, `bandwidth`, and frame duration.
    pub fn parse(b: u8) -> Self {
        let config = b >> 3;
        let stereo = (b >> 2) & 1 != 0;
        let code = b & 0x3;
        let (mode, bandwidth, frame_samples_48k) = decode_config(config);
        Self {
            config,
            mode,
            bandwidth,
            frame_samples_48k,
            stereo,
            code,
        }
    }

    /// Channel count encoded in the TOC (`1` mono or `2` stereo).
    pub fn channels(&self) -> u16 {
        if self.stereo {
            2
        } else {
            1
        }
    }
}

/// Map the 5-bit `config` field to (mode, bandwidth, samples-per-frame at 48 kHz).
/// Exact layout from RFC 6716 Table 2.
fn decode_config(config: u8) -> (OpusMode, OpusBandwidth, u32) {
    // Note: SILK frames are natively at 8/12/16 kHz, CELT at 48 kHz, hybrid
    // at 48 kHz with SILK @ 16 kHz internally. At the decoder output they
    // are all resampled to 48 kHz; the `frame_samples_48k` reflects that.
    match config {
        // SILK-only, NB, 10/20/40/60 ms — 480/960/1920/2880 samples @48k
        0 => (OpusMode::SilkOnly, OpusBandwidth::Narrowband, 480),
        1 => (OpusMode::SilkOnly, OpusBandwidth::Narrowband, 960),
        2 => (OpusMode::SilkOnly, OpusBandwidth::Narrowband, 1920),
        3 => (OpusMode::SilkOnly, OpusBandwidth::Narrowband, 2880),
        // SILK-only, MB
        4 => (OpusMode::SilkOnly, OpusBandwidth::Mediumband, 480),
        5 => (OpusMode::SilkOnly, OpusBandwidth::Mediumband, 960),
        6 => (OpusMode::SilkOnly, OpusBandwidth::Mediumband, 1920),
        7 => (OpusMode::SilkOnly, OpusBandwidth::Mediumband, 2880),
        // SILK-only, WB
        8 => (OpusMode::SilkOnly, OpusBandwidth::Wideband, 480),
        9 => (OpusMode::SilkOnly, OpusBandwidth::Wideband, 960),
        10 => (OpusMode::SilkOnly, OpusBandwidth::Wideband, 1920),
        11 => (OpusMode::SilkOnly, OpusBandwidth::Wideband, 2880),
        // Hybrid, SWB, 10/20 ms
        12 => (OpusMode::Hybrid, OpusBandwidth::SuperWideband, 480),
        13 => (OpusMode::Hybrid, OpusBandwidth::SuperWideband, 960),
        // Hybrid, FB, 10/20 ms
        14 => (OpusMode::Hybrid, OpusBandwidth::Fullband, 480),
        15 => (OpusMode::Hybrid, OpusBandwidth::Fullband, 960),
        // CELT-only, NB, 2.5/5/10/20 ms = 120/240/480/960 @48k
        16 => (OpusMode::CeltOnly, OpusBandwidth::Narrowband, 120),
        17 => (OpusMode::CeltOnly, OpusBandwidth::Narrowband, 240),
        18 => (OpusMode::CeltOnly, OpusBandwidth::Narrowband, 480),
        19 => (OpusMode::CeltOnly, OpusBandwidth::Narrowband, 960),
        // CELT-only, WB
        20 => (OpusMode::CeltOnly, OpusBandwidth::Wideband, 120),
        21 => (OpusMode::CeltOnly, OpusBandwidth::Wideband, 240),
        22 => (OpusMode::CeltOnly, OpusBandwidth::Wideband, 480),
        23 => (OpusMode::CeltOnly, OpusBandwidth::Wideband, 960),
        // CELT-only, SWB
        24 => (OpusMode::CeltOnly, OpusBandwidth::SuperWideband, 120),
        25 => (OpusMode::CeltOnly, OpusBandwidth::SuperWideband, 240),
        26 => (OpusMode::CeltOnly, OpusBandwidth::SuperWideband, 480),
        27 => (OpusMode::CeltOnly, OpusBandwidth::SuperWideband, 960),
        // CELT-only, FB
        28 => (OpusMode::CeltOnly, OpusBandwidth::Fullband, 120),
        29 => (OpusMode::CeltOnly, OpusBandwidth::Fullband, 240),
        30 => (OpusMode::CeltOnly, OpusBandwidth::Fullband, 480),
        31 => (OpusMode::CeltOnly, OpusBandwidth::Fullband, 960),
        // `config` is 5 bits, so this is unreachable.
        _ => (OpusMode::CeltOnly, OpusBandwidth::Fullband, 960),
    }
}

/// A single Opus packet after TOC parsing. Holds zero-copy slices into the
/// caller's buffer.
#[derive(Debug)]
pub struct OpusPacket<'a> {
    pub toc: Toc,
    /// Per-frame byte slices. Length is 1..=48.
    pub frames: Vec<&'a [u8]>,
    /// Optional padding bytes (discarded content, RFC §3.2.5).
    pub padding: &'a [u8],
}

/// Read a single RFC 6716 §3.2.1 length value (one or two bytes).
///
/// Returns `(length, bytes_consumed)`.
fn read_length(data: &[u8]) -> Result<(usize, usize)> {
    let b0 = *data
        .first()
        .ok_or_else(|| Error::invalid("Opus frame length truncated"))?;
    if b0 < 252 {
        Ok((b0 as usize, 1))
    } else {
        let b1 = *data
            .get(1)
            .ok_or_else(|| Error::invalid("Opus frame length truncated (2-byte)"))?;
        Ok(((b1 as usize * 4) + b0 as usize, 2))
    }
}

/// Parse a full Opus packet (TOC + framing) per RFC 6716 §3.
///
/// The returned `frames` slices reference `data` directly — no copies.
pub fn parse_packet(data: &[u8]) -> Result<OpusPacket<'_>> {
    if data.is_empty() {
        return Err(Error::invalid("Opus packet empty (needs ≥ 1 TOC byte)"));
    }
    let toc = Toc::parse(data[0]);
    let body = &data[1..];

    match toc.code {
        // Code 0: one single frame fills the remaining bytes.
        0 => Ok(OpusPacket {
            toc,
            frames: vec![body],
            padding: &[],
        }),
        // Code 1: two equal-sized frames, remaining bytes split in half.
        1 => {
            if body.len() % 2 != 0 {
                return Err(Error::invalid(
                    "Opus code-1 packet: body length must be even",
                ));
            }
            let half = body.len() / 2;
            Ok(OpusPacket {
                toc,
                frames: vec![&body[..half], &body[half..]],
                padding: &[],
            })
        }
        // Code 2: two frames of possibly-different sizes. Length of first
        // frame is coded in 1..=2 bytes; second frame takes the rest.
        2 => {
            let (n1, used) = read_length(body)?;
            let rest = &body[used..];
            if n1 > rest.len() {
                return Err(Error::invalid(
                    "Opus code-2 packet: frame-1 length exceeds payload",
                ));
            }
            Ok(OpusPacket {
                toc,
                frames: vec![&rest[..n1], &rest[n1..]],
                padding: &[],
            })
        }
        // Code 3: N frames, with a dedicated framing byte.
        3 => parse_code3(toc, body),
        _ => unreachable!(),
    }
}

/// Parse a self-delimited Opus packet per RFC 6716 Appendix B.
///
/// Self-delimited framing is used for the first N-1 sub-streams of a
/// multistream packet (RFC 7845 §5.1.1): the packet carries its own
/// length information so the parser can tell where this sub-stream
/// ends and the next one begins without external framing.
///
/// The rules vary by code (from Appendix B):
///
/// * **Code 0** — 1 frame. Add a 1-or-2-byte length giving the frame
///   size.
/// * **Code 1** — 2 equal frames. Add a length giving the size of
///   *each* frame.
/// * **Code 2** — 2 unequal frames. Already has length for the first
///   frame. Add a length for the second frame.
/// * **Code 3 CBR** — N CBR frames. Add a length giving the size of
///   each frame.
/// * **Code 3 VBR** — N VBR frames. Already has N-1 lengths. Add a
///   length for the Nth frame.
///
/// Returns `(OpusPacket, bytes_consumed)` — the caller advances its
/// input cursor by `bytes_consumed` before parsing the next sub-stream.
pub fn parse_self_delimited_packet(data: &[u8]) -> Result<(OpusPacket<'_>, usize)> {
    if data.is_empty() {
        return Err(Error::invalid("self-delimited Opus packet empty"));
    }
    let toc = Toc::parse(data[0]);
    let mut cursor = 1usize;

    match toc.code {
        0 => {
            let (n, used) = read_length(&data[cursor..])?;
            cursor += used;
            if cursor + n > data.len() {
                return Err(Error::invalid(
                    "self-delimited code-0: frame exceeds buffer",
                ));
            }
            let frames = vec![&data[cursor..cursor + n]];
            cursor += n;
            Ok((
                OpusPacket {
                    toc,
                    frames,
                    padding: &[],
                },
                cursor,
            ))
        }
        1 => {
            let (n, used) = read_length(&data[cursor..])?;
            cursor += used;
            if cursor + 2 * n > data.len() {
                return Err(Error::invalid(
                    "self-delimited code-1: 2 frames exceed buffer",
                ));
            }
            let f1 = &data[cursor..cursor + n];
            let f2 = &data[cursor + n..cursor + 2 * n];
            cursor += 2 * n;
            Ok((
                OpusPacket {
                    toc,
                    frames: vec![f1, f2],
                    padding: &[],
                },
                cursor,
            ))
        }
        2 => {
            let (n1, u1) = read_length(&data[cursor..])?;
            cursor += u1;
            let (n2, u2) = read_length(&data[cursor..])?;
            cursor += u2;
            if cursor + n1 + n2 > data.len() {
                return Err(Error::invalid(
                    "self-delimited code-2: frames exceed buffer",
                ));
            }
            let f1 = &data[cursor..cursor + n1];
            let f2 = &data[cursor + n1..cursor + n1 + n2];
            cursor += n1 + n2;
            Ok((
                OpusPacket {
                    toc,
                    frames: vec![f1, f2],
                    padding: &[],
                },
                cursor,
            ))
        }
        3 => {
            // Same frame-count / padding structure as the regular
            // parser, but with an extra explicit length for the last
            // frame.
            let body = &data[cursor..];
            if body.is_empty() {
                return Err(Error::invalid(
                    "self-delimited code-3: missing frame-count byte",
                ));
            }
            let fc = body[0];
            let vbr = fc & 0x80 != 0;
            let has_padding = fc & 0x40 != 0;
            let n_frames = (fc & 0x3F) as usize;
            if n_frames == 0 {
                return Err(Error::invalid("self-delimited code-3: 0 frames"));
            }
            let mut body_cur = 1usize;

            let mut pad_bytes = 0usize;
            if has_padding {
                loop {
                    if body_cur >= body.len() {
                        return Err(Error::invalid(
                            "self-delimited code-3: padding length truncated",
                        ));
                    }
                    let p = body[body_cur];
                    body_cur += 1;
                    if p == 255 {
                        pad_bytes += 254;
                    } else {
                        pad_bytes += p as usize;
                        break;
                    }
                }
            }

            let mut frame_sizes: Vec<usize> = Vec::with_capacity(n_frames);
            if vbr {
                // N-1 lengths for frames 0..N-2, plus 1 explicit
                // length for the Nth frame (self-delimited extension).
                for _ in 0..n_frames {
                    let (len, used) = read_length(&body[body_cur..])?;
                    frame_sizes.push(len);
                    body_cur += used;
                }
            } else {
                // CBR: 1 explicit length giving the size of each
                // (equal-sized) frame.
                let (len, used) = read_length(&body[body_cur..])?;
                body_cur += used;
                for _ in 0..n_frames {
                    frame_sizes.push(len);
                }
            }

            let total_frame_bytes: usize = frame_sizes.iter().sum();
            if body_cur + total_frame_bytes + pad_bytes > body.len() {
                return Err(Error::invalid(
                    "self-delimited code-3: frame data exceeds buffer",
                ));
            }

            let data_start_in_body = body_cur;
            let mut frames: Vec<&[u8]> = Vec::with_capacity(n_frames);
            let mut pos = data_start_in_body;
            for &sz in &frame_sizes {
                frames.push(&body[pos..pos + sz]);
                pos += sz;
            }
            let padding_start = pos;
            let consumed = cursor + padding_start + pad_bytes;
            Ok((
                OpusPacket {
                    toc,
                    frames,
                    padding: &body[padding_start..padding_start + pad_bytes],
                },
                consumed,
            ))
        }
        _ => unreachable!(),
    }
}

/// Code-3 packet parsing per RFC 6716 §3.2.5.
fn parse_code3<'a>(toc: Toc, body: &'a [u8]) -> Result<OpusPacket<'a>> {
    if body.is_empty() {
        return Err(Error::invalid(
            "Opus code-3 packet: missing frame-count byte",
        ));
    }
    let fc = body[0];
    let vbr = fc & 0x80 != 0;
    let has_padding = fc & 0x40 != 0;
    let n_frames = (fc & 0x3F) as usize;
    if n_frames == 0 {
        return Err(Error::invalid("Opus code-3 packet: frame count is 0"));
    }
    // Soft spec limit: total frame duration <= 120 ms. With config-dependent
    // frame sizes that never exceeds 48 frames even at the shortest size.
    if n_frames > 48 {
        return Err(Error::invalid(
            "Opus code-3 packet: frame count exceeds 48 (>120 ms)",
        ));
    }
    let samples_per = toc.frame_samples_48k as usize;
    if samples_per * n_frames > 5760 {
        return Err(Error::invalid(
            "Opus code-3 packet: total duration > 120 ms",
        ));
    }

    let mut cursor = 1usize;

    // Padding length (if signalled). The padding-length field itself can
    // span multiple bytes: each byte 0xFF contributes 254 and indicates
    // "another byte follows", and the final byte contributes its own value.
    let mut pad_bytes = 0usize;
    if has_padding {
        loop {
            if cursor >= body.len() {
                return Err(Error::invalid(
                    "Opus code-3 packet: padding length truncated",
                ));
            }
            let p = body[cursor];
            cursor += 1;
            if p == 255 {
                pad_bytes += 254;
            } else {
                pad_bytes += p as usize;
                break;
            }
        }
    }

    // Per-frame length table when VBR is on; otherwise every frame has the
    // same size = (remaining_after_padding) / n_frames.
    let mut frame_sizes = Vec::with_capacity(n_frames);
    if vbr {
        for _ in 0..n_frames - 1 {
            let (len, used) = read_length(&body[cursor..])?;
            frame_sizes.push(len);
            cursor += used;
        }
    }

    // Calculate where frame data actually begins and how much is left for it.
    let data_end = body
        .len()
        .checked_sub(pad_bytes)
        .ok_or_else(|| Error::invalid("Opus code-3 packet: padding exceeds body"))?;
    if cursor > data_end {
        return Err(Error::invalid(
            "Opus code-3 packet: headers overflow past data region",
        ));
    }
    let data_region = &body[cursor..data_end];

    if !vbr {
        if data_region.len() % n_frames != 0 {
            return Err(Error::invalid(
                "Opus code-3 CBR packet: body not divisible by frame count",
            ));
        }
        let each = data_region.len() / n_frames;
        for _ in 0..n_frames {
            frame_sizes.push(each);
        }
    } else {
        // For VBR, the last frame consumes the remainder.
        let explicit_total: usize = frame_sizes.iter().sum();
        if explicit_total > data_region.len() {
            return Err(Error::invalid(
                "Opus code-3 VBR packet: coded lengths exceed body size",
            ));
        }
        frame_sizes.push(data_region.len() - explicit_total);
    }

    // Split the data region into per-frame slices.
    let mut frames = Vec::with_capacity(n_frames);
    let mut pos = 0usize;
    for &sz in &frame_sizes {
        if pos + sz > data_region.len() {
            return Err(Error::invalid(
                "Opus code-3 packet: frame slice runs past body",
            ));
        }
        frames.push(&data_region[pos..pos + sz]);
        pos += sz;
    }

    Ok(OpusPacket {
        toc,
        frames,
        padding: &body[data_end..],
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn toc_config_celt_20ms_fb_stereo() {
        // config=31 (CELT-only FB 20 ms), stereo=1, code=0.
        let b = (31 << 3) | (1 << 2);
        let t = Toc::parse(b);
        assert_eq!(t.config, 31);
        assert_eq!(t.mode, OpusMode::CeltOnly);
        assert_eq!(t.bandwidth, OpusBandwidth::Fullband);
        assert_eq!(t.frame_samples_48k, 960);
        assert!(t.stereo);
        assert_eq!(t.code, 0);
    }

    #[test]
    fn toc_silk_nb_mono() {
        let t = Toc::parse(0);
        assert_eq!(t.mode, OpusMode::SilkOnly);
        assert_eq!(t.bandwidth, OpusBandwidth::Narrowband);
        assert!(!t.stereo);
    }

    #[test]
    fn toc_hybrid_fb() {
        // config=15 — Hybrid FB 20 ms.
        let t = Toc::parse(15 << 3);
        assert_eq!(t.mode, OpusMode::Hybrid);
        assert_eq!(t.bandwidth, OpusBandwidth::Fullband);
        assert_eq!(t.frame_samples_48k, 960);
    }

    #[test]
    fn parse_code0_single_frame() {
        let mut p = vec![31u8 << 3]; // TOC: config=31, stereo=0, code=0
        p.extend_from_slice(&[0xAA, 0xBB, 0xCC]);
        let pkt = parse_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 1);
        assert_eq!(pkt.frames[0], &[0xAA, 0xBB, 0xCC]);
    }

    #[test]
    fn parse_code1_two_equal_frames() {
        let mut p = vec![(31u8 << 3) | 1];
        p.extend_from_slice(&[1, 2, 3, 4]);
        let pkt = parse_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 2);
        assert_eq!(pkt.frames[0], &[1, 2]);
        assert_eq!(pkt.frames[1], &[3, 4]);
    }

    #[test]
    fn parse_code1_rejects_odd_body() {
        let mut p = vec![(31u8 << 3) | 1];
        p.extend_from_slice(&[1, 2, 3]);
        assert!(parse_packet(&p).is_err());
    }

    #[test]
    fn parse_code2_two_frames_short_length() {
        // TOC=code-2, length byte = 3, frame-1 bytes, then frame-2 bytes.
        let mut p = vec![(31u8 << 3) | 2, 3];
        p.extend_from_slice(&[1, 2, 3]); // frame 1
        p.extend_from_slice(&[9, 9]); // frame 2
        let pkt = parse_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 2);
        assert_eq!(pkt.frames[0], &[1, 2, 3]);
        assert_eq!(pkt.frames[1], &[9, 9]);
    }

    #[test]
    fn parse_code2_two_frames_long_length() {
        // Long length = 252 + 4*1 = 256 bytes.
        let mut p = vec![(31u8 << 3) | 2, 252, 1];
        p.extend(std::iter::repeat_n(0x5A, 256));
        p.extend_from_slice(&[0xAA, 0xBB]);
        let pkt = parse_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 2);
        assert_eq!(pkt.frames[0].len(), 256);
        assert_eq!(pkt.frames[1], &[0xAA, 0xBB]);
    }

    #[test]
    fn parse_code3_cbr_three_frames() {
        // TOC=code-3 | CELT 2.5ms config 16, fc=3 frames, no VBR, no padding.
        let mut p = vec![(16u8 << 3) | 3, 3];
        p.extend_from_slice(&[1, 2, 3, 4, 5, 6]);
        let pkt = parse_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 3);
        assert_eq!(pkt.frames[0], &[1, 2]);
        assert_eq!(pkt.frames[1], &[3, 4]);
        assert_eq!(pkt.frames[2], &[5, 6]);
    }

    #[test]
    fn parse_code3_vbr_three_frames_with_padding() {
        // TOC=code-3 | CELT 2.5ms NB; fc=0xC3 (VBR, padding, count=3);
        // pad=2; f1 len=1; f2 len=2; then data f1/f2/f3 then padding.
        let mut p = vec![(16u8 << 3) | 3, 0xC3, 2, 1, 2, 0xA];
        p.extend_from_slice(&[0xB, 0xC]);
        p.extend_from_slice(&[0xD, 0xD, 0xD, 0xD]);
        // padding bytes
        p.extend_from_slice(&[0, 0]);
        let pkt = parse_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 3);
        assert_eq!(pkt.frames[0], &[0xA]);
        assert_eq!(pkt.frames[1], &[0xB, 0xC]);
        assert_eq!(pkt.frames[2], &[0xD, 0xD, 0xD, 0xD]);
        assert_eq!(pkt.padding, &[0, 0]);
    }

    #[test]
    fn parse_code3_rejects_zero_frames() {
        let p = vec![(16u8 << 3) | 3, 0x00];
        assert!(parse_packet(&p).is_err());
    }

    #[test]
    fn parse_empty_packet_errors() {
        assert!(parse_packet(&[]).is_err());
    }

    /// RFC 6716 Appendix B / RFC 7845 §5.1.1 self-delimited framing:
    /// a code-0 packet in self-delimited form has a 1-byte length
    /// prepended to the single frame.
    #[test]
    fn parse_self_delimited_code0() {
        // TOC=code-0 (config=31 stereo=0), length=3, frame bytes 0xAA 0xBB 0xCC,
        // then trailing bytes that belong to the *next* sub-stream.
        let mut p = vec![31u8 << 3, 3, 0xAA, 0xBB, 0xCC];
        p.extend_from_slice(&[0xFF, 0xFF]);
        let (pkt, consumed) = parse_self_delimited_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 1);
        assert_eq!(pkt.frames[0], &[0xAA, 0xBB, 0xCC]);
        // TOC + length(1) + frame(3) = 5 bytes consumed; 2 bytes
        // remain for the next sub-stream.
        assert_eq!(consumed, 5);
    }

    /// Self-delimited code-1: two equal frames, 1 length = per-frame size.
    #[test]
    fn parse_self_delimited_code1() {
        let mut p = vec![(31u8 << 3) | 1, 2, 0x10, 0x20, 0x30, 0x40];
        p.extend_from_slice(&[0x99]);
        let (pkt, consumed) = parse_self_delimited_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 2);
        assert_eq!(pkt.frames[0], &[0x10, 0x20]);
        assert_eq!(pkt.frames[1], &[0x30, 0x40]);
        assert_eq!(consumed, 6); // TOC + len + 2*2
    }

    /// Self-delimited code-2: two possibly-different frames, both
    /// lengths explicitly coded.
    #[test]
    fn parse_self_delimited_code2() {
        let mut p = vec![(31u8 << 3) | 2, 1, 3, 0xAA, 0xBB, 0xBB, 0xBB];
        p.extend_from_slice(&[0x00, 0x00]);
        let (pkt, consumed) = parse_self_delimited_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 2);
        assert_eq!(pkt.frames[0], &[0xAA]);
        assert_eq!(pkt.frames[1], &[0xBB, 0xBB, 0xBB]);
        // TOC + 2 length bytes + 1 + 3 = 7.
        assert_eq!(consumed, 7);
    }

    /// Self-delimited code-3 CBR: 1 explicit length = per-frame size.
    #[test]
    fn parse_self_delimited_code3_cbr() {
        // TOC=code-3 | CELT 2.5ms NB, fc=3 (3 frames, no VBR, no pad),
        // length=2, then 3*2=6 bytes of frame data.
        let mut p = vec![(16u8 << 3) | 3, 3, 2, 1, 2, 3, 4, 5, 6];
        p.push(0xEE);
        let (pkt, consumed) = parse_self_delimited_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 3);
        assert_eq!(pkt.frames[0], &[1, 2]);
        assert_eq!(pkt.frames[1], &[3, 4]);
        assert_eq!(pkt.frames[2], &[5, 6]);
        assert_eq!(consumed, 9); // TOC + fc + len + 6
    }

    /// Self-delimited code-3 VBR: N explicit lengths (N-1 for interior
    /// frames + 1 for the final frame).
    #[test]
    fn parse_self_delimited_code3_vbr() {
        // fc = 0x83 = VBR + 3 frames. lens = 1, 2, 3. frames = A, BC, DEF.
        let p = vec![(16u8 << 3) | 3, 0x83, 1, 2, 3, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF];
        let (pkt, consumed) = parse_self_delimited_packet(&p).unwrap();
        assert_eq!(pkt.frames.len(), 3);
        assert_eq!(pkt.frames[0], &[0xA]);
        assert_eq!(pkt.frames[1], &[0xB, 0xC]);
        assert_eq!(pkt.frames[2], &[0xD, 0xE, 0xF]);
        // TOC + fc + 3 len bytes + 1 + 2 + 3 = 11.
        assert_eq!(consumed, 11);
    }
}