opus1 0.3.0

Pure-Rust implementation of the Opus audio codec (RFC 6716), following libopus 1.x
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
//! Multistream Opus: several Opus streams in one packet, for audio with more
//! than two channels (RFC 7845 section 5.1.1, libopus `opus_multistream_*`).
//!
//! A multistream packet holds one ordinary Opus packet per stream. The first
//! streams are stereo ("coupled" streams), the others are mono. Every stream
//! has its own [`OpusEncoder`](crate::OpusEncoder) or
//! [`OpusDecoder`](crate::OpusDecoder), so the codec itself never sees more
//! than 2 channels. A channel layout says which stream each channel of the
//! application goes to or comes from.
//!
//! What is here:
//!
//! - [`MultistreamEncoder`](crate::multistream::MultistreamEncoder):
//!   encodes interleaved samples into a multistream packet. A port of
//!   libopus `opus_multistream_encoder.c` (`src/multistream/encoder.rs`).
//!   Its surround masking analysis is in `src/multistream/surround.rs`, and
//!   how it divides a bitrate among the streams in
//!   `src/multistream/rate_alloc.rs`.
//! - [`MultistreamDecoder`](crate::multistream::MultistreamDecoder): decodes
//!   a multistream packet into interleaved samples. A port of libopus
//!   `opus_multistream_decoder.c` (`src/multistream/decoder.rs`).
//! - [`ChannelLayout`](crate::multistream::ChannelLayout): the layout, its
//!   checks, and the layouts of the mapping families of the Ogg Opus header
//!   (`src/multistream/layout.rs`).
//!   [`validate_ambisonics`](crate::multistream::validate_ambisonics) checks
//!   the channel count of an ambisonics layout.
//! - [`ChannelMappingTable`](crate::multistream::ChannelMappingTable): the
//!   channel mapping table as it is stored in an Ogg Opus header.
//! - [`split_self_delimited`](crate::multistream::split_self_delimited):
//!   cuts one stream out of a multistream packet, for code that wants to
//!   look at the streams itself. The decoder does not need it.
//!
//! The module needs the `alloc` feature, which the default features `std`
//! and `heap` turn on. It works in a `no_std` build that has a global
//! allocator. The number of streams is known only at run time (up to 255),
//! so the stream encoders and decoders live in a `Vec`. Memory is allocated
//! when an encoder or a decoder is built, and each stream codec is built in
//! place in it ([`OpusEncoder::init`](crate::OpusEncoder::init),
//! [`OpusDecoder::init`](crate::OpusDecoder::init)), so building needs
//! little stack, also without `heap`. Encoding, decoding and `reset_state`
//! allocate nothing.
//!
//! Both [`MultistreamEncoder`](crate::multistream::MultistreamEncoder) and
//! [`MultistreamDecoder`](crate::multistream::MultistreamDecoder) have the
//! same three constructors: `new` takes the layout as numbers,
//! `from_mapping_table` takes the table of an Ogg Opus header, and
//! `from_layout` takes a checked
//! [`ChannelLayout`](crate::multistream::ChannelLayout). The encoder also
//! has `new_surround`, which picks the layout of a mapping family.
//!
//! # Encoding
//!
//! [`MultistreamEncoder::new_surround`](crate::multistream::MultistreamEncoder::new_surround)
//! picks the layout of a mapping family of the Ogg Opus header. Family 1 is
//! the one for surround sound: 1 to 8 channels in the channel order of
//! Vorbis. With more than 2 channels the encoder works in surround mode. It
//! then codes the stereo pairs with CELT and spends fewer bits on what
//! other channels mask. With 6, 7 or 8 channels the last channel is the
//! low-frequency-effects (LFE) channel, which gets a small stream of its
//! own.
//!
//! ```
//! use core::num::NonZeroU32;
//! use opus1::multistream::MultistreamEncoder;
//! use opus1::{Application, Bitrate, SampleRate};
//!
//! // 5.1 at 48 kHz: front left, centre, front right, rear left, rear
//! // right, LFE.
//! let mut encoder = MultistreamEncoder::new_surround(SampleRate::Hz48000, 6, 1, Application::Audio)?;
//! encoder.set_bitrate(Bitrate::BitsPerSecond(NonZeroU32::new(256_000).unwrap()));
//!
//! // Two stereo streams (front and rear), then the centre and the LFE
//! // channel as mono streams. An Ogg Opus header stores these numbers and
//! // the mapping.
//! let layout = encoder.layout();
//! assert_eq!((layout.streams(), layout.coupled_streams()), (4, 2));
//! assert_eq!(layout.mapping(), &[0, 4, 1, 2, 3, 5]);
//! assert_eq!(encoder.lfe_stream(), Some(3));
//!
//! // One frame of 20 ms: 960 samples per channel, interleaved. Sample `i`
//! // of channel `c` is `pcm[i * 6 + c]`.
//! let pcm: Vec<f32> = (0..960 * 6)
//!     .map(|k| 0.2 * ((k / 6) as f32 * 0.02 * (1 + k % 6) as f32).sin())
//!     .collect();
//! // The length of the buffer is the largest packet allowed.
//! let mut packet = vec![0u8; 4000];
//! let len = encoder.encode(&pcm, 960, &mut packet)?;
//! assert!(len > 0 && len <= packet.len());
//! # Ok::<(), opus1::Error>(())
//! ```
//!
//! # Decoding
//!
//! The decoder needs the layout the encoder used: the number of channels,
//! of streams and of coupled streams, and the mapping. A file carries them
//! in its header. A packet does not, so a decoder with another layout reads
//! it wrongly or rejects it.
//!
//! ```
//! use opus1::multistream::{MultistreamDecoder, MultistreamEncoder};
//! use opus1::{Application, SampleRate};
//!
//! // A packet to decode: one 20 ms frame of quadraphonic sound.
//! let mut encoder = MultistreamEncoder::new_surround(SampleRate::Hz48000, 4, 1, Application::Audio)?;
//! let pcm = vec![0.1f32; 960 * 4];
//! let mut packet = vec![0u8; 4000];
//! let len = encoder.encode(&pcm, 960, &mut packet)?;
//!
//! // The decoder for the same layout.
//! let mut decoder = MultistreamDecoder::from_layout(SampleRate::Hz48000, encoder.layout())?;
//! assert_eq!(decoder.channels(), 4);
//!
//! // `out` has room for 960 samples per channel. The result is the number
//! // of samples per channel that were written, interleaved like the input.
//! let mut out = vec![0f32; 960 * 4];
//! let samples = decoder.decode(&packet[..len], 960, &mut out)?;
//! assert_eq!(samples, 960);
//!
//! // An empty packet stands for a lost one: the decoder fills the gap.
//! let samples = decoder.decode(&[], 960, &mut out)?;
//! assert_eq!(samples, 960);
//! # Ok::<(), opus1::Error>(())
//! ```
//!
//! The decoder writes the output channels in the order of its mapping
//! table. For mapping family 1 that is the channel order of Vorbis, for
//! example front left, centre, front right, rear left, rear right and LFE
//! for 5.1. A WAV file orders the same channels differently. The decoder
//! does not reorder or downmix the channels; that is left to the
//! application.
//!
//! `examples/multistream.rs` encodes and decodes a longer 5.1 signal and
//! prints the packet sizes and the quality of every channel.

// The links in the text above are written with their full path on purpose.
// `src/lib.rs` puts a line of documentation in front of that text, and
// rustdoc then resolves the links of both from the crate root.

mod decoder;
mod encoder;
mod layout;
pub(crate) mod rate_alloc;
pub(crate) mod surround;

pub use decoder::MultistreamDecoder;
pub use encoder::MultistreamEncoder;
pub use layout::{ChannelLayout, MappingType, SILENT_CHANNEL, validate_ambisonics};

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use crate::Error;
use crate::{float2int16, float2int24, int16_to_res, int24_to_res, packet};

/// Source of the input samples of one frame, by input channel.
/// libopus calls this `opus_copy_channel_in_func`.
pub(crate) trait ChannelSource {
    /// Writes `frame_size` samples of input channel `channel` to
    /// `dst[..frame_size]`.
    fn copy(&self, dst: &mut [f32], channel: usize, frame_size: usize);
}

/// A sample type of the encoder input and the decoder output: `f32` with
/// full scale 1.0, `i16`, or `i32` holding 24-bit samples.
pub(crate) trait Sample: Copy {
    /// Silence.
    const ZERO: Self;
    /// The precision libopus gives this input type: 24 bits for `f32` and
    /// `i32` (`MAX_ENCODING_DEPTH`) and 16 for `i16`.
    const LSB_DEPTH: i32;
    /// The `float_api` argument libopus's multistream encoder passes for
    /// this input type: 1 for `f32`, 0 for `i16` and `i32`.
    const FLOAT_API: bool;
    /// The samples as the speech and music analysis reads them: libopus
    /// `downmix_float` for `f32`, `downmix_int` for `i16` and
    /// `downmix_int24` for `i32`.
    fn analysis_pcm(pcm: &[Self]) -> crate::analysis::PcmRef<'_>;
    /// The sample as `f32` with full scale 1.0.
    fn to_f32(self) -> f32;
    /// An `f32` sample with full scale 1.0 as this type.
    fn from_f32(v: f32) -> Self;
}

impl Sample for f32 {
    const ZERO: f32 = 0.0;
    const LSB_DEPTH: i32 = 24;
    const FLOAT_API: bool = true;

    #[inline(always)]
    fn analysis_pcm(pcm: &[f32]) -> crate::analysis::PcmRef<'_> {
        crate::analysis::PcmRef::F32(pcm)
    }

    #[inline(always)]
    fn to_f32(self) -> f32 {
        self
    }

    #[inline(always)]
    fn from_f32(v: f32) -> f32 {
        v
    }
}

impl Sample for i16 {
    const ZERO: i16 = 0;
    const LSB_DEPTH: i32 = 16;
    const FLOAT_API: bool = false;

    #[inline(always)]
    fn analysis_pcm(pcm: &[i16]) -> crate::analysis::PcmRef<'_> {
        crate::analysis::PcmRef::I16(pcm)
    }

    /// libopus `INT16TORES` in the float build.
    #[inline(always)]
    fn to_f32(self) -> f32 {
        int16_to_res(self)
    }

    /// libopus `FLOAT2INT16`: rounded to the nearest integer and limited to
    /// the 16-bit range.
    #[inline(always)]
    fn from_f32(v: f32) -> i16 {
        float2int16(v)
    }
}

impl Sample for i32 {
    const ZERO: i32 = 0;
    const LSB_DEPTH: i32 = 24;
    const FLOAT_API: bool = false;

    #[inline(always)]
    fn analysis_pcm(pcm: &[i32]) -> crate::analysis::PcmRef<'_> {
        crate::analysis::PcmRef::I32(pcm)
    }

    /// libopus `INT24TORES` in the float build.
    #[inline(always)]
    fn to_f32(self) -> f32 {
        int24_to_res(self)
    }

    /// libopus `RES2INT24`: scaled by 2^23 and rounded to the nearest
    /// integer, without a limit to 24 bits.
    #[inline(always)]
    fn from_f32(v: f32) -> i32 {
        float2int24(v)
    }
}

/// Interleaved input: sample `i` of channel `c` is `pcm[i * channels + c]`.
/// libopus `opus_copy_channel_in_float` and `opus_copy_channel_in_short`.
///
/// A copy writes fewer samples when `pcm` or the destination is shorter
/// than the frame. It writes nothing for a channel the input does not have.
pub(crate) struct Interleaved<'a, T> {
    pub(crate) pcm: &'a [T],
    pub(crate) channels: usize,
}

impl<T: Sample> Interleaved<'_, T> {
    /// Writes `frame_size` samples of channels `left` and `right` to `dst`,
    /// interleaved: sample `i` of `left` to `dst[2 * i]` and of `right` to
    /// `dst[2 * i + 1]`. This is the input of a coupled stream.
    #[inline]
    pub(crate) fn copy_pair(&self, dst: &mut [f32], left: usize, right: usize, frame_size: usize) {
        if left >= self.channels || right >= self.channels {
            return;
        }
        let pairs = dst.as_chunks_mut::<2>().0.iter_mut();
        let frames = self.pcm.chunks_exact(self.channels);
        for (d, frame) in pairs.zip(frames).take(frame_size) {
            *d = [frame[left].to_f32(), frame[right].to_f32()];
        }
    }
}

impl<T: Sample> ChannelSource for Interleaved<'_, T> {
    #[inline]
    fn copy(&self, dst: &mut [f32], channel: usize, frame_size: usize) {
        if channel >= self.channels {
            return;
        }
        let frames = self.pcm.chunks_exact(self.channels);
        for (d, frame) in dst.iter_mut().zip(frames).take(frame_size) {
            *d = frame[channel].to_f32();
        }
    }
}

/// Destination of the decoded samples of one frame, by output channel.
/// libopus calls this `opus_copy_channel_out_func`.
pub(crate) trait ChannelSink {
    /// Writes `frame_size` samples to output channel `dst_channel`.
    /// `src` is `Some((samples, stride, channel))`: the samples of a stream
    /// with `stride` channels, interleaved, and the channel to copy. Sample
    /// `i` is `samples[i * stride + channel]`. `None` writes silence.
    fn put(&mut self, dst_channel: usize, src: Option<(&[f32], usize, usize)>, frame_size: usize);
}

/// The channel mapping table of an Ogg Opus header (RFC 7845 section 5.1.1):
/// the bytes that follow the fixed 19-byte part of `OpusHead` when the
/// mapping family is not 0.
///
/// A table read from a file is not checked.
/// [`MultistreamDecoder::from_mapping_table`] and
/// [`MultistreamEncoder::from_mapping_table`] check it.
///
/// The fields can be read and changed. More fields may come in a later
/// release, so a value is built with [`new`](Self::new) or
/// [`parse`](Self::parse).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChannelMappingTable {
    /// Number of output channels.
    pub channels: u8,
    /// Number of streams in one packet.
    pub stream_count: u8,
    /// Number of stereo streams. They are the first streams of a packet; the
    /// others are mono.
    pub coupled_count: u8,
    /// One entry per output channel: the decoded channel it uses, or
    /// [`SILENT_CHANNEL`] for silence. Decoded channels are numbered as
    /// [`ChannelLayout`] describes: 2 per stereo stream first, then 1 per mono
    /// stream.
    pub mapping: Vec<u8>,
}

impl ChannelMappingTable {
    /// A table with these values. Nothing is checked, as for a table read
    /// from a file.
    ///
    /// ```
    /// use opus1::multistream::ChannelMappingTable;
    ///
    /// // The 5.1 layout of mapping family 1: 4 streams, 2 of them stereo.
    /// let table = ChannelMappingTable::new(6, 4, 2, &[0, 4, 1, 2, 3, 5]);
    /// assert_eq!(table.mapping, [0, 4, 1, 2, 3, 5]);
    /// ```
    pub fn new(channels: u8, stream_count: u8, coupled_count: u8, mapping: &[u8]) -> Self {
        Self {
            channels,
            stream_count,
            coupled_count,
            mapping: mapping.to_vec(),
        }
    }

    /// Reads the table. `tail` starts right after the output gain of
    /// `OpusHead`, at byte 19 of the header.
    ///
    /// Returns `None` for mapping family 0, which has no table, and when
    /// `tail` is too short.
    pub fn parse(mapping_family: u8, channels: u8, tail: &[u8]) -> Option<Self> {
        if mapping_family == 0 || tail.len() < 2 + channels as usize {
            return None;
        }
        Some(Self {
            channels,
            stream_count: tail[0],
            coupled_count: tail[1],
            mapping: tail[2..2 + channels as usize].to_vec(),
        })
    }
}

/// Cuts the first stream out of a multistream packet.
///
/// Every stream of a multistream packet but the last is "self-delimited"
/// (RFC 6716 appendix B): it carries one size field more than an ordinary
/// packet, for its last frame, so that a reader knows where the stream ends.
///
/// `data` starts with a self-delimited packet. The function copies it into
/// `scratch` without the extra size field. The result is an ordinary Opus
/// packet that any decoder accepts. Returns that packet and the number of
/// bytes the stream takes in `data`, which is where the next stream starts.
///
/// `scratch` is cleared first. Its memory is reused, so a caller that splits
/// many packets allocates once.
///
/// The framing is checked with [`packet::parse`], which follows libopus. A
/// packet that libopus rejects is an error.
pub fn split_self_delimited<'a>(
    data: &[u8],
    scratch: &'a mut Vec<u8>,
) -> Result<(&'a [u8], usize), Error> {
    const INVALID: Error = Error::INVALID_PACKET;
    let parsed = packet::parse(data, packet::Framing::SelfDelimited)?;
    // The extra field is the last thing before the first frame. It holds the
    // size of the last frame.
    let last_size = parsed.frame_sizes().last().copied().ok_or(INVALID)?;
    let field_len = packet::size_field_len(last_size);
    let header_end = parsed.payload_offset().checked_sub(field_len).ok_or(INVALID)?;
    let header = data.get(..header_end).ok_or(INVALID)?;
    let frames_and_padding = data.get(parsed.payload_offset()..parsed.packet_offset()).ok_or(INVALID)?;
    scratch.clear();
    scratch.extend_from_slice(header);
    scratch.extend_from_slice(frames_and_padding);
    Ok((scratch.as_slice(), parsed.packet_offset()))
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;
    use crate::packet::{Framing, Padding};

    fn toc_byte(config: u8, stereo: bool, code: u8) -> u8 {
        (config << 3) | ((stereo as u8) << 2) | (code & 0x03)
    }

    #[test]
    fn interleaved_input_gives_one_channel_or_a_pair() {
        // 3 channels, 4 samples: channel c holds 10 * c + i.
        let pcm: Vec<f32> = (0..12).map(|k| (10 * (k % 3) + k / 3) as f32).collect();
        let src = Interleaved {
            pcm: &pcm,
            channels: 3,
        };
        let mut mono = [-1.0f32; 6];
        src.copy(&mut mono, 2, 4);
        assert_eq!(mono, [20.0, 21.0, 22.0, 23.0, -1.0, -1.0]);
        let mut stereo = [-1.0f32; 10];
        src.copy_pair(&mut stereo, 0, 1, 4);
        assert_eq!(stereo, [0.0, 10.0, 1.0, 11.0, 2.0, 12.0, 3.0, 13.0, -1.0, -1.0]);
        // The right channel of a pair may come before the left one.
        src.copy_pair(&mut stereo, 2, 0, 2);
        assert_eq!(&stereo[..4], [20.0, 0.0, 21.0, 1.0]);
    }

    #[test]
    fn interleaved_input_never_reads_or_writes_out_of_range() {
        let pcm = [1.0f32; 7];
        let src = Interleaved {
            pcm: &pcm,
            channels: 2,
        };
        // More samples asked for than the input and the destination hold.
        let mut dst = [0.0f32; 2];
        src.copy(&mut dst, 1, 100);
        assert_eq!(dst, [1.0, 1.0]);
        let mut dst = [0.0f32; 5];
        src.copy_pair(&mut dst, 0, 1, 100);
        assert_eq!(dst, [1.0, 1.0, 1.0, 1.0, 0.0]);
        // A channel that does not exist copies nothing.
        let mut dst = [0.0f32; 4];
        src.copy(&mut dst, 2, 2);
        src.copy_pair(&mut dst, 0, 2, 2);
        src.copy_pair(&mut dst, 2, 1, 2);
        assert_eq!(dst, [0.0; 4]);
    }

    #[test]
    fn sixteen_bit_input_is_scaled_by_32768() {
        let pcm = [i16::MIN, -1, 0, 1, 16384, i16::MAX];
        let src = Interleaved {
            pcm: &pcm,
            channels: 1,
        };
        let mut dst = [9.0f32; 6];
        src.copy(&mut dst, 0, 6);
        assert_eq!(
            dst,
            [
                -1.0,
                -1.0 / 32768.0,
                0.0,
                1.0 / 32768.0,
                0.5,
                32767.0 / 32768.0
            ]
        );
    }

    #[test]
    fn mapping_table_parses_5_1_shape() {
        let tail = [4u8, 2, 0, 1, 4, 5, 2, 3];
        let table = ChannelMappingTable::parse(1, 6, &tail).unwrap();
        assert_eq!(table.stream_count, 4);
        assert_eq!(table.coupled_count, 2);
        assert_eq!(table.mapping, vec![0, 1, 4, 5, 2, 3]);
    }

    #[test]
    fn mapping_family_zero_has_no_table() {
        assert!(ChannelMappingTable::parse(0, 2, &[9, 9, 9, 9]).is_none());
    }

    #[test]
    fn mapping_table_rejects_truncated_tail() {
        assert!(ChannelMappingTable::parse(1, 6, &[4, 2, 0, 1]).is_none());
    }

    #[test]
    fn split_code0_single_frame() {
        let bytes = [toc_byte(0, false, 0), 3, 0xAA, 0xBB, 0xCC, 0xFF];
        let mut scratch = Vec::new();
        let (pkt, consumed) = split_self_delimited(&bytes, &mut scratch).unwrap();
        assert_eq!(consumed, 1 + 1 + 3);
        // reconstructed packet excises the length byte: TOC + frame data only
        assert_eq!(pkt, &[toc_byte(0, false, 0), 0xAA, 0xBB, 0xCC][..]);
    }

    #[test]
    fn split_code0_two_byte_length() {
        let mut bytes = vec![toc_byte(0, false, 0), 252, 0];
        bytes.extend(std::iter::repeat_n(0x7Fu8, 252));
        let mut scratch = Vec::new();
        let (_, consumed) = split_self_delimited(&bytes, &mut scratch).unwrap();
        assert_eq!(consumed, 1 + 2 + 252);
    }

    #[test]
    fn split_code1_equal_frames() {
        let bytes = [toc_byte(0, false, 1), 2, 0xAA, 0xBB, 0xCC, 0xDD, 0x11];
        let mut scratch = Vec::new();
        let (_, consumed) = split_self_delimited(&bytes, &mut scratch).unwrap();
        assert_eq!(consumed, 1 + 1 + 4);
    }

    #[test]
    fn split_code2_two_lengths() {
        let bytes = [toc_byte(0, false, 2), 3, 2, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE];
        let mut scratch = Vec::new();
        let (pkt, consumed) = split_self_delimited(&bytes, &mut scratch).unwrap();
        assert_eq!(consumed, 1 + 1 + 1 + 3 + 2);
        // inline length (3, for frame 1) is kept; the extra Appendix B
        // length (2, for frame 2) is excised
        assert_eq!(pkt, &[toc_byte(0, false, 2), 3, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE][..]);
    }

    #[test]
    fn split_code3_cbr_three_frames() {
        let bytes = [toc_byte(0, false, 3), 3, 2, 0x10, 0x11, 0x20, 0x21, 0x30, 0x31];
        let mut scratch = Vec::new();
        let (_, consumed) = split_self_delimited(&bytes, &mut scratch).unwrap();
        assert_eq!(consumed, 1 + 1 + 1 + 6);
    }

    #[test]
    fn split_code3_cbr_with_padding() {
        let fc = 0x40 | 2u8;
        let bytes = [
            toc_byte(0, false, 3), fc, 2, 3,
            0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
            0x55, 0x66,
        ];
        let mut scratch = Vec::new();
        let (_, consumed) = split_self_delimited(&bytes, &mut scratch).unwrap();
        assert_eq!(consumed, 12);
    }

    #[test]
    fn split_code3_vbr_three_frames() {
        let fc = 0x80 | 3u8;
        let bytes = [
            toc_byte(0, false, 3), fc, 2, 3, 1,
            0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
        ];
        let mut scratch = Vec::new();
        let (pkt, consumed) = split_self_delimited(&bytes, &mut scratch).unwrap();
        assert_eq!(consumed, 1 + 1 + 1 + 1 + 1 + 2 + 3 + 1);
        // inline lengths for frames 1-2 (2, 3) are kept; the extra
        // Appendix B length for frame 3 (1) is excised
        assert_eq!(pkt, &[toc_byte(0, false, 3), fc, 2, 3, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF][..]);
    }

    #[test]
    fn split_two_streams_chained() {
        let bytes = [
            toc_byte(0, false, 0), 2, 0xA0, 0xA1,
            toc_byte(0, false, 1), 1, 0xB0, 0xB1,
        ];
        let mut scratch = Vec::new();
        let a_consumed = {
            let (a, a_consumed) = split_self_delimited(&bytes, &mut scratch).unwrap();
            // reconstructed: TOC + frame data, length byte excised
            assert_eq!(a, &[toc_byte(0, false, 0), 0xA0, 0xA1][..]);
            a_consumed
        };
        assert_eq!(a_consumed, 4);
        let (_, b_consumed) = split_self_delimited(&bytes[a_consumed..], &mut scratch).unwrap();
        assert_eq!(b_consumed, 4);
    }

    #[test]
    fn split_truncated_frame_is_error() {
        let bytes = [toc_byte(0, false, 0), 4, 0xAA, 0xBB];
        let mut scratch = Vec::new();
        assert!(split_self_delimited(&bytes, &mut scratch).is_err());
    }

    #[test]
    fn split_code3_zero_frames_is_error() {
        let bytes = [toc_byte(0, false, 3), 0, 1, 0xAA];
        let mut scratch = Vec::new();
        assert!(split_self_delimited(&bytes, &mut scratch).is_err());
    }

    #[test]
    fn split_gives_the_packet_that_packet_write_gives() {
        // Write the same frames as a self-delimited and as an ordinary
        // packet. Splitting the first must give the second.
        let big = [0x5Au8; 600];
        let cases: [(&[&[u8]], Padding); 9] = [
            (&[&big[..0]], Padding::Shortest),
            (&[&big[..1]], Padding::Shortest),
            (&[&big[..251]], Padding::Shortest),
            (&[&big[..252]], Padding::Shortest),
            (&[&big[..600]], Padding::Shortest),
            (&[&big[..300], &big[..300]], Padding::Shortest),
            (&[&big[..7], &big[..300]], Padding::Shortest),
            (&[&big[..3], &big[..3], &big[..3]], Padding::FillBuffer),
            (&[&big[..10], &big[..253], &big[..0], &big[..40]], Padding::FillBuffer),
        ];
        // SILK narrowband 10 ms, so that 4 frames stay below 120 ms.
        let toc = toc_byte(0, false, 0);
        for (frames, pad) in cases {
            let mut delimited = [0u8; 2000];
            let mut ordinary = [0u8; 2000];
            let (len_d, len_o) = if pad == Padding::FillBuffer {
                // Padding fills the whole buffer that is given.
                let total: usize = frames.iter().map(|f| f.len()).sum();
                (total + 40, total + 37)
            } else {
                (2000, 2000)
            };
            let n_d = packet::write(toc, frames, &mut delimited[..len_d], Framing::SelfDelimited, pad).unwrap();
            let n_o = packet::write(toc, frames, &mut ordinary[..len_o], Framing::Normal, pad).unwrap();
            // Bytes of another stream follow the self-delimited packet.
            delimited[n_d..n_d + 3].copy_from_slice(&[0xEE; 3]);
            let mut scratch = vec![1, 2, 3];
            let (pkt, consumed) = split_self_delimited(&delimited[..n_d + 3], &mut scratch).unwrap();
            assert_eq!(consumed, n_d, "{} frames", frames.len());
            let parsed = packet::parse(pkt, Framing::Normal).unwrap();
            assert_eq!(parsed.nb_frames(), frames.len());
            for (i, frame) in frames.iter().enumerate() {
                assert_eq!(parsed.frame(pkt, i), *frame, "frame {i}");
            }
            if pad == Padding::Shortest {
                assert_eq!(pkt, &ordinary[..n_o], "{} frames", frames.len());
            }
        }
    }

    #[test]
    fn split_rejects_what_libopus_rejects() {
        let mut scratch = Vec::new();
        // No byte at all, and a TOC byte without its size field.
        assert!(split_self_delimited(&[], &mut scratch).is_err());
        assert!(split_self_delimited(&[toc_byte(0, false, 0)], &mut scratch).is_err());
        // A 2-byte size field cut after its first byte.
        assert!(split_self_delimited(&[toc_byte(0, false, 0), 252], &mut scratch).is_err());
        // 13 SILK 10 ms frames are more than 120 ms.
        let mut long = vec![toc_byte(0, false, 3), 13, 1];
        long.extend_from_slice(&[0u8; 13]);
        assert!(split_self_delimited(&long, &mut scratch).is_err());
    }
}