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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
//! Opus packet framing (RFC 6716 section 3 and appendix B): reading the
//! frames out of a packet, writing frames into a packet, and padding.
//!
//! This is a port of the framing code of libopus 1.6: `opus_packet_parse_impl`
//! (opus.c), the repacketizer with `opus_packet_pad` and
//! `opus_packet_unpad` (repacketizer.c), and
//! `opus_multistream_packet_validate` (opus_multistream_decoder.c).
//!
//! Nothing here allocates, apart from the rare cases that
//! [`pad_with_extensions`] and [`Repacketizer::out_range_ext`] describe. A packet is described by a small [`ParsedPacket`]
//! value and the frames stay where they are, in the caller's buffer.
//!
//! A packet starts with a table-of-contents (TOC) byte. Its two lowest bits
//! are the frame-count code:
//!
//! - code 0: one frame.
//! - code 1: two frames of the same size.
//! - code 2: two frames of different sizes.
//! - code 3: any number of frames, of one size (CBR) or with a size each
//!   (VBR), and optional padding at the end.
//!
//! "Self-delimited" framing (RFC 6716 appendix B,
//! [`Framing::SelfDelimited`]) adds the size of the last frame, so that a
//! decoder knows where the packet ends. A multistream packet uses it for
//! every stream but the last.
//!
//! The TOC byte also gives the mode, the audio bandwidth ([`bandwidth`]), the
//! frame duration ([`samples_per_frame`]) and the channel count
//! ([`nb_channels`]).
//!
//! The padding of a code 3 packet can hold packet extensions (libopus 1.5
//! and later; see [`crate::extensions`]). As in libopus:
//!
//! - [`parse`] does not look at the padding; [`ParsedPacket::padding`]
//!   returns it.
//! - [`Repacketizer`] carries the extensions of its packets into the
//!   packets it writes, with frame numbers that count from the first frame
//!   of the new packet.
//! - [`pad`] and [`multistream_pad`] keep the extensions of the packet, and
//!   fail with [`InternalError`](crate::ErrorKind::InternalError) when its
//!   padding holds invalid extension data. [`pad_with_extensions`] adds
//!   extensions.
//! - [`unpad`] and [`multistream_unpad`] drop the padding with its
//!   extensions.
//!
//! The decoder ignores extensions, as libopus 1.6.1 without its quality
//! extension (QEXT) does.

use crate::{Bandwidth, Channels, Error, SampleRate};
use crate::extensions::{self, Extension, ExtensionIterator, ExtensionList};
use crate::fixedvec::FixedVec;

/// The most frames a packet can hold: 120 ms of 2.5 ms frames.
pub const MAX_FRAMES: usize = 48;
/// The largest frame the size fields can express.
pub const MAX_FRAME_BYTES: usize = 1275;
/// The most audio one packet holds: 120 ms, in samples per channel at
/// 48 kHz.
pub(crate) const MAX_PACKET_SAMPLES: usize = max_packet_samples(48000);

/// The most audio one packet holds, 120 ms, in samples per channel at `fs`
/// samples per second.
#[inline]
pub(crate) const fn max_packet_samples(fs: i32) -> usize {
    fs as usize / 25 * 3
}

/// How a packet shows where it ends: libopus's `self_delimited` flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Framing {
    /// The packet ends where its data ends (RFC 6716 section 3). The last
    /// frame takes the bytes that are left.
    Normal,
    /// The packet also codes the size of its last frame (RFC 6716
    /// appendix B), so other data can follow it. Every stream but the last
    /// of a multistream packet has this framing.
    SelfDelimited,
}

impl Framing {
    /// [`Framing::SelfDelimited`] when `self_delimited` is true: the libopus
    /// flag as a `Framing`.
    pub(crate) const fn from_flag(self_delimited: bool) -> Self {
        if self_delimited { Framing::SelfDelimited } else { Framing::Normal }
    }

    const fn is_self_delimited(self) -> bool {
        matches!(self, Framing::SelfDelimited)
    }
}

/// How long a written packet or list of extensions is: libopus's `pad`
/// flag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Padding {
    /// No more bytes than the content needs.
    Shortest,
    /// Padding fills the output buffer, so the result takes exactly the
    /// length of the buffer.
    FillBuffer,
}

impl Padding {
    /// [`Padding::FillBuffer`] when `pad` is true: the libopus flag as a
    /// `Padding`.
    pub(crate) const fn from_flag(pad: bool) -> Self {
        if pad { Padding::FillBuffer } else { Padding::Shortest }
    }

    pub(crate) const fn fills_buffer(self) -> bool {
        matches!(self, Padding::FillBuffer)
    }
}

/// Result of parsing one Opus packet: libopus `opus_packet_parse_impl`.
///
/// It holds the sizes and offsets that [`parse`] found, not the bytes. Pass
/// the parsed `data` to [`frames`](Self::frames), [`frame`](Self::frame) and
/// [`padding`](Self::padding) to get the bytes.
#[derive(Debug, Clone, Copy)]
pub struct ParsedPacket {
    toc: u8,
    /// Number of frames, 1..=48.
    count: usize,
    /// Size of each frame in bytes; only `sizes[..count]` is meaningful.
    sizes: [u16; MAX_FRAMES],
    payload_offset: usize,
    packet_offset: usize,
    /// Never more than `packet_offset`.
    padding_len: usize,
}

impl ParsedPacket {
    /// The table-of-contents (TOC) byte.
    pub fn toc(&self) -> u8 {
        self.toc
    }

    /// The number of frames, 1 to 48.
    pub fn nb_frames(&self) -> usize {
        self.count
    }

    /// The size of each frame in bytes, in the order of the frames.
    /// libopus `size` of `opus_packet_parse`.
    pub fn frame_sizes(&self) -> &[u16] {
        &self.sizes[..self.count]
    }

    /// Where the first frame starts, in bytes from the start of the packet.
    /// libopus `payload_offset` of `opus_packet_parse`.
    pub fn payload_offset(&self) -> usize {
        self.payload_offset
    }

    /// The bytes the packet takes, padding included. For a self-delimited
    /// packet this is where the data after it starts, such as the next
    /// stream of a multistream packet. libopus `packet_offset` of
    /// `opus_packet_parse_impl`.
    pub fn packet_offset(&self) -> usize {
        self.packet_offset
    }

    /// The bytes of padding at the end of the packet: the last
    /// `padding_len()` bytes before [`packet_offset`](Self::packet_offset).
    /// libopus `padding_len` of `opus_packet_parse_impl`.
    pub fn padding_len(&self) -> usize {
        self.padding_len
    }

    /// The frames of the packet `data` this value was parsed from, in order.
    pub fn frames<'a>(&self, data: &'a [u8]) -> Frames<'a, '_> {
        Frames {
            data,
            sizes: &self.sizes[..self.count],
            offset: self.payload_offset,
        }
    }

    /// Frame `index` of the packet `data` this value was parsed from. An
    /// index past the last frame gives an empty slice.
    pub fn frame<'a>(&self, data: &'a [u8], index: usize) -> &'a [u8] {
        self.frames(data).nth(index).unwrap_or(&[])
    }

    /// The padding of the packet `data` this value was parsed from: the
    /// [`padding_len`](Self::padding_len) bytes after the last frame, where
    /// packet extensions live (see [`crate::extensions`]). libopus returns
    /// it from `opus_packet_parse_impl`. When `data` is not that packet and
    /// is too short, the result is empty.
    pub fn padding<'a>(&self, data: &'a [u8]) -> &'a [u8] {
        data.get(self.packet_offset - self.padding_len..self.packet_offset).unwrap_or(&[])
    }
}

/// Iterator over the frames of a parsed packet, see [`ParsedPacket::frames`].
#[derive(Debug, Clone)]
pub struct Frames<'a, 'p> {
    data: &'a [u8],
    sizes: &'p [u16],
    offset: usize,
}

impl<'a> Iterator for Frames<'a, '_> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<&'a [u8]> {
        let (&size, rest) = self.sizes.split_first()?;
        self.sizes = rest;
        let start = self.offset;
        self.offset += size as usize;
        // `parse` checked that every frame lies inside the packet. The
        // fallback only matters when `data` is not that packet.
        Some(self.data.get(start..self.offset).unwrap_or(&[]))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.sizes.len(), Some(self.sizes.len()))
    }
}

impl ExactSizeIterator for Frames<'_, '_> {}

/// libopus `opus_packet_get_samples_per_frame`: the duration of one frame of
/// a packet with this TOC byte, in samples at `sampling_rate`.
pub fn samples_per_frame(toc: u8, sampling_rate: SampleRate) -> usize {
    let fs = sampling_rate.hz() as i64;
    let audiosize = if toc & 0x80 != 0 {
        // CELT-only: 2.5, 5, 10 or 20 ms.
        (fs << ((toc >> 3) & 0x3)) / 400
    } else if toc & 0x60 == 0x60 {
        // Hybrid: 10 or 20 ms.
        if toc & 0x08 != 0 { fs / 50 } else { fs / 100 }
    } else {
        // SILK-only: 10, 20, 40 or 60 ms.
        let shift = (toc >> 3) & 0x3;
        if shift == 3 { fs * 60 / 1000 } else { (fs << shift) / 100 }
    };
    audiosize as usize
}

/// libopus `opus_packet_get_bandwidth`: the audio bandwidth of a packet with
/// this TOC byte.
///
/// SILK-only packets are narrowband, mediumband or wideband, Hybrid packets
/// superwideband or fullband. CELT-only packets have no mediumband: their
/// configurations 16 to 19 are narrowband.
pub fn bandwidth(toc: u8) -> Bandwidth {
    if toc & 0x80 != 0 {
        // CELT-only.
        match (toc >> 5) & 0x3 {
            0 => Bandwidth::Narrowband,
            1 => Bandwidth::Wideband,
            2 => Bandwidth::Superwideband,
            _ => Bandwidth::Fullband,
        }
    } else if toc & 0x60 == 0x60 {
        // Hybrid.
        if toc & 0x10 != 0 { Bandwidth::Fullband } else { Bandwidth::Superwideband }
    } else {
        // SILK-only: bits 5 and 6 are 0, 1 or 2 here, since 3 is Hybrid.
        match (toc >> 5) & 0x3 {
            0 => Bandwidth::Narrowband,
            1 => Bandwidth::Mediumband,
            _ => Bandwidth::Wideband,
        }
    }
}

/// libopus `opus_packet_get_nb_channels`: the number of channels a packet
/// with this TOC byte codes, from its stereo flag (bit 2).
pub fn nb_channels(toc: u8) -> Channels {
    if toc & 0x4 != 0 { Channels::Stereo } else { Channels::Mono }
}

/// libopus `opus_packet_get_nb_frames`: the number of frames a packet says
/// it holds. Only the first two bytes are looked at; [`parse`] checks the
/// rest.
pub fn nb_frames(data: &[u8]) -> Result<usize, Error> {
    let Some(&toc) = data.first() else {
        return Err(Error::BAD_ARG);
    };
    match toc & 0x3 {
        0 => Ok(1),
        1 | 2 => Ok(2),
        _ => match data.get(1) {
            Some(&count) => Ok((count & 0x3F) as usize),
            None => Err(Error::INVALID_PACKET),
        },
    }
}

/// libopus `opus_packet_get_nb_samples`: the duration of a packet in
/// samples per channel at `sampling_rate`. More than 120 ms is invalid.
pub fn nb_samples(data: &[u8], sampling_rate: SampleRate) -> Result<usize, Error> {
    let samples = nb_frames(data)? * samples_per_frame(data[0], sampling_rate);
    if samples as i64 * 25 > sampling_rate.hz() as i64 * 3 {
        return Err(Error::INVALID_PACKET);
    }
    Ok(samples)
}

/// libopus `opus_packet_has_lbrr`: whether a packet carries a low-bitrate
/// redundant (LBRR) copy of the frame before it in its first SILK frame,
/// the copy that in-band forward error correction (FEC) decodes.
///
/// - A CELT-only packet has none. It gives `false` without being parsed.
/// - Other packets are parsed, and an invalid packet is an error.
/// - The flag is read from the first byte of the first frame: the LBRR flag
///   of the mid channel, and for a stereo packet also that of the side
///   channel. A first frame of 0 bytes has none.
///
/// An empty `data` is an error. (libopus reads the byte before it checks
/// the length.)
pub fn has_lbrr(data: &[u8]) -> Result<bool, Error> {
    let Some(&toc) = data.first() else {
        return Err(Error::INVALID_PACKET);
    };
    if toc & 0x80 != 0 {
        return Ok(false);
    }
    // The SILK frames of one Opus frame: one per 20 ms.
    let frame_size = samples_per_frame(toc, SampleRate::Hz48000);
    let nb_frames = if frame_size > 960 { frame_size / 960 } else { 1 };
    let stereo = toc & 0x4 != 0;
    let parsed = parse(data, Framing::Normal)?;
    let Some(&first) = parsed.frame(data, 0).first() else {
        return Ok(false);
    };
    // The first byte starts with the activity flag of each SILK frame and
    // then the LBRR flag, for the mid channel and then the side channel.
    let mut lbrr = (first >> (7 - nb_frames)) & 1 != 0;
    if stereo {
        lbrr = lbrr || (first >> (6 - 2 * nb_frames)) & 1 != 0;
    }
    Ok(lbrr)
}

/// libopus `encode_size` (opus.c): the number of bytes a frame size takes.
#[inline]
pub(crate) fn size_field_len(size: u16) -> usize {
    1 + (size >= 252) as usize
}

/// libopus `encode_size` (opus.c): write a frame size, return the number of
/// bytes written (1 or 2).
#[inline]
fn encode_size(size: u16, out: &mut [u8]) -> usize {
    if size < 252 {
        out[0] = size as u8;
        1
    } else {
        let first = 252 + (size & 0x3);
        out[0] = first as u8;
        out[1] = ((size - first) >> 2) as u8;
        2
    }
}

/// libopus `parse_size` (opus.c): read a frame size at `data[pos]` when
/// `len` bytes are left. Returns the number of bytes read and the size, or
/// `None` when the field is cut short.
#[inline]
fn parse_size(data: &[u8], pos: usize, len: i64) -> Option<(i64, i64)> {
    if len < 1 {
        return None;
    }
    let first = *data.get(pos)? as i64;
    if first < 252 {
        Some((1, first))
    } else if len < 2 {
        None
    } else {
        Some((2, 4 * (*data.get(pos + 1)? as i64) + first))
    }
}

/// Parse the framing of one Opus packet: libopus `opus_packet_parse_impl`
/// (opus.c).
///
/// With [`Framing::SelfDelimited`], `data` starts with a self-delimited
/// packet and may continue with other data, such as the next stream of a
/// multistream packet. [`ParsedPacket::packet_offset`] then says where the
/// packet ends.
///
/// Returns an error wherever libopus returns `OPUS_INVALID_PACKET`.
pub fn parse(data: &[u8], framing: Framing) -> Result<ParsedPacket, Error> {
    let self_delimited = framing.is_self_delimited();
    let Some(&toc) = data.first() else {
        return Err(Error::INVALID_PACKET);
    };
    let framesize = samples_per_frame(toc, SampleRate::Hz48000);

    // `pos` is the next byte to read. `len` is the C variable of the same
    // name: the bytes left for sizes and frames. It is signed because the
    // padding of a corrupt packet can claim more bytes than there are.
    let mut pos = 1usize;
    let mut len = data.len() as i64 - 1;
    let mut last_size = len;
    let mut cbr = false;
    let mut pad = 0i64;
    let mut sizes = [0u16; MAX_FRAMES];
    let count: usize;

    match toc & 0x3 {
        // One frame.
        0 => count = 1,
        // Two frames of the same size.
        1 => {
            count = 2;
            cbr = true;
            if !self_delimited {
                if len & 0x1 != 0 {
                    return Err(Error::INVALID_PACKET);
                }
                last_size = len / 2;
            }
        }
        // Two frames of different sizes.
        2 => {
            count = 2;
            let Some((bytes, size)) = parse_size(data, pos, len) else {
                return Err(Error::INVALID_PACKET);
            };
            len -= bytes;
            if size > len {
                return Err(Error::INVALID_PACKET);
            }
            pos += bytes as usize;
            sizes[0] = size as u16;
            last_size = len - size;
        }
        // Any number of frames, 0 to 120 ms in total.
        _ => {
            if len < 1 {
                return Err(Error::INVALID_PACKET);
            }
            // The number of frames is in bits 0 to 5.
            let ch = data[pos];
            pos += 1;
            count = (ch & 0x3F) as usize;
            if count == 0 || framesize * count > MAX_PACKET_SAMPLES {
                return Err(Error::INVALID_PACKET);
            }
            len -= 1;
            // Bit 6 says that padding follows.
            if ch & 0x40 != 0 {
                loop {
                    if len <= 0 {
                        return Err(Error::INVALID_PACKET);
                    }
                    let p = data[pos];
                    pos += 1;
                    len -= 1;
                    let tmp = if p == 255 { 254 } else { p as i64 };
                    len -= tmp;
                    pad += tmp;
                    if p != 255 {
                        break;
                    }
                }
            }
            if len < 0 {
                return Err(Error::INVALID_PACKET);
            }
            // Bit 7 says that the frames have a size each (VBR).
            cbr = ch & 0x80 == 0;
            if !cbr {
                last_size = len;
                for size_out in sizes.iter_mut().take(count - 1) {
                    let Some((bytes, size)) = parse_size(data, pos, len) else {
                        return Err(Error::INVALID_PACKET);
                    };
                    len -= bytes;
                    if size > len {
                        return Err(Error::INVALID_PACKET);
                    }
                    pos += bytes as usize;
                    *size_out = size as u16;
                    last_size -= bytes + size;
                }
                if last_size < 0 {
                    return Err(Error::INVALID_PACKET);
                }
            } else if !self_delimited {
                last_size = len / count as i64;
                if last_size * count as i64 != len {
                    return Err(Error::INVALID_PACKET);
                }
            }
        }
    }

    if self_delimited {
        // Self-delimited framing has an extra size for the last frame.
        let Some((bytes, size)) = parse_size(data, pos, len) else {
            return Err(Error::INVALID_PACKET);
        };
        len -= bytes;
        if size > len {
            return Err(Error::INVALID_PACKET);
        }
        pos += bytes as usize;
        if cbr {
            // For CBR packets the size applies to all the frames.
            if size * count as i64 > len {
                return Err(Error::INVALID_PACKET);
            }
            sizes[..count].fill(size as u16);
        } else {
            if bytes + size > last_size {
                return Err(Error::INVALID_PACKET);
            }
            sizes[count - 1] = size as u16;
        }
    } else {
        // The size of the last frame (of all frames for CBR) is not coded,
        // so it can come out larger than a frame may be.
        if last_size > MAX_FRAME_BYTES as i64 {
            return Err(Error::INVALID_PACKET);
        }
        if cbr {
            sizes[..count].fill(last_size as u16);
        } else {
            sizes[count - 1] = last_size as u16;
        }
    }

    let frame_bytes: usize = sizes[..count].iter().map(|&s| s as usize).sum();
    Ok(ParsedPacket {
        toc,
        count,
        sizes,
        payload_offset: pos,
        packet_offset: pad as usize + pos + frame_bytes,
        padding_len: pad as usize,
    })
}

/// libopus `opus_multistream_packet_validate` (opus_multistream_decoder.c):
/// check the framing of a multistream packet of `nb_streams` streams.
///
/// Every stream but the last is self-delimited. All streams must have the
/// same duration. Returns that duration in samples per channel at
/// `sampling_rate`.
pub fn multistream_validate(
    data: &[u8],
    nb_streams: usize,
    sampling_rate: SampleRate,
) -> Result<usize, Error> {
    if nb_streams == 0 {
        return Err(Error::BAD_ARG);
    }
    let mut rest = data;
    let mut samples = 0usize;
    for s in 0..nb_streams {
        if rest.is_empty() {
            return Err(Error::INVALID_PACKET);
        }
        let packet = parse(rest, Framing::from_flag(s != nb_streams - 1))?;
        // opus_packet_get_nb_samples: no more than 120 ms.
        let tmp_samples = packet.count * samples_per_frame(packet.toc, sampling_rate);
        if tmp_samples as i64 * 25 > sampling_rate.hz() as i64 * 3 {
            return Err(Error::INVALID_PACKET);
        }
        if s != 0 && samples != tmp_samples {
            return Err(Error::INVALID_PACKET);
        }
        samples = tmp_samples;
        rest = rest.get(packet.packet_offset..).ok_or(Error::INVALID_PACKET)?;
    }
    Ok(samples)
}

/// Where the parts of a packet go: the decisions
/// `opus_repacketizer_out_range_impl` makes before it writes anything.
struct Layout {
    /// Frame-count code, 0..=3.
    code: u8,
    /// Code 3 only: the frames have a size each.
    vbr: bool,
    /// Code 3 only: bytes of padding, counting the bytes that code its
    /// length.
    pad_amount: usize,
    /// Bytes before the first frame.
    header_len: usize,
    /// Bytes of the extensions, which end the padding.
    ext_len: usize,
    /// Length of the whole packet.
    total: usize,
}

/// Lay out a packet of frames with the given `sizes` and `extensions` in
/// at most `maxlen` bytes: the first half of
/// `opus_repacketizer_out_range_impl`.
fn layout(
    sizes: &[u16],
    maxlen: usize,
    self_delimited: bool,
    pad: bool,
    extensions: &[Extension],
) -> Result<Layout, Error> {
    let count = sizes.len();
    let payload: usize = sizes.iter().map(|&s| s as usize).sum();
    // Self-delimited framing codes the size of the last frame as well.
    let last_size_len = if self_delimited { size_field_len(sizes[count - 1]) } else { 0 };

    let mut code = 3u8;
    let mut header_len = 0usize;
    if count == 1 {
        code = 0;
        header_len = 1;
    } else if count == 2 {
        if sizes[1] == sizes[0] {
            code = 1;
            header_len = 1;
        } else {
            code = 2;
            header_len = 1 + size_field_len(sizes[0]);
        }
    }
    header_len += last_size_len;
    if count <= 2 && header_len + payload > maxlen {
        return Err(Error::BUFFER_TOO_SMALL);
    }

    let mut vbr = false;
    let mut pad_amount = 0usize;
    let mut ext_len = 0usize;
    if count > 2 || (pad && header_len + payload < maxlen) || !extensions.is_empty() {
        // Code 3. Padding and extensions need it whatever the number of
        // frames.
        code = 3;
        vbr = sizes[1..].iter().any(|&s| s != sizes[0]);
        header_len = 2 + last_size_len;
        if vbr {
            header_len += sizes[..count - 1].iter().map(|&s| size_field_len(s)).sum::<usize>();
        }
        let tot_size = header_len + payload;
        if tot_size > maxlen {
            return Err(Error::BUFFER_TOO_SMALL);
        }
        if pad {
            pad_amount = maxlen - tot_size;
        }
        if !extensions.is_empty() {
            ext_len = extensions::generated_len(maxlen - tot_size, extensions, count)?;
            if !pad {
                // Just the room of the extensions and of the length.
                pad_amount = ext_len + if ext_len > 0 { ext_len.div_ceil(254) } else { 1 };
            }
        }
        if pad_amount != 0 {
            // The length of the padding takes `nb_255s + 1` bytes of it.
            let nb_255s = (pad_amount - 1) / 255;
            if tot_size + ext_len + nb_255s + 1 > maxlen {
                return Err(Error::BUFFER_TOO_SMALL);
            }
            header_len += nb_255s + 1;
        }
        return Ok(Layout { code, vbr, pad_amount, header_len, ext_len, total: tot_size + pad_amount });
    }
    Ok(Layout { code, vbr, pad_amount, header_len, ext_len, total: header_len + payload })
}

/// Write the bytes before the first frame into `out[..plan.header_len]`:
/// the TOC byte, the frame count, the padding length and the frame sizes.
fn write_header(toc: u8, sizes: &[u16], plan: &Layout, self_delimited: bool, out: &mut [u8]) {
    let count = sizes.len();
    out[0] = (toc & 0xFC) | plan.code;
    let mut pos = 1usize;
    if plan.code == 2 {
        pos += encode_size(sizes[0], &mut out[pos..]);
    } else if plan.code == 3 {
        out[1] = count as u8 | if plan.vbr { 0x80 } else { 0 };
        pos = 2;
        if plan.pad_amount != 0 {
            out[1] |= 0x40;
            let nb_255s = (plan.pad_amount - 1) / 255;
            out[pos..pos + nb_255s].fill(255);
            pos += nb_255s;
            out[pos] = (plan.pad_amount - 255 * nb_255s - 1) as u8;
            pos += 1;
        }
        if plan.vbr {
            for &size in &sizes[..count - 1] {
                pos += encode_size(size, &mut out[pos..]);
            }
        }
    }
    if self_delimited {
        pos += encode_size(sizes[count - 1], &mut out[pos..]);
    }
    debug_assert_eq!(pos, plan.header_len);
}

/// Write one packet into `out`, whose length is the most the packet may
/// take: libopus `opus_repacketizer_out_range_impl` once it has collected
/// the extensions.
///
/// `place_frames(out, at)` puts the frames, one after the other, at offset
/// `at` of `out`. It runs before anything else is written, so that it can
/// move frames that are already in `out` (in-place padding).
///
/// After the frames comes the padding: with extensions, bytes 0x01 and then
/// the extensions; with `pad` and no extensions, zeros up to the end of
/// `out`.
fn emit(
    toc: u8,
    sizes: &[u16],
    out: &mut [u8],
    self_delimited: bool,
    pad: bool,
    extensions: &[Extension],
    place_frames: impl FnOnce(&mut [u8], usize),
) -> Result<usize, Error> {
    let plan = layout(sizes, out.len(), self_delimited, pad, extensions)?;
    place_frames(out, plan.header_len);
    write_header(toc, sizes, &plan, self_delimited, out);
    let pos = plan.header_len + sizes.iter().map(|&s| s as usize).sum::<usize>();
    if !extensions.is_empty() {
        let ext_begin = plan.total - plan.ext_len;
        out[pos..ext_begin].fill(0x01);
        let written = extensions::generate(&mut out[ext_begin..plan.total], extensions, sizes.len(), Padding::Shortest);
        debug_assert_eq!(written, Ok(plan.ext_len));
    } else if pad {
        // Fill the padding with zeros.
        out[pos..].fill(0);
    }
    Ok(plan.total)
}

/// Check the frames a packet is to be made of, and collect their sizes.
fn frame_sizes(toc: u8, frames: &[&[u8]]) -> Result<[u16; MAX_FRAMES], Error> {
    let count = frames.len();
    // The repacketizer takes no more than 120 ms of audio
    // (opus_repacketizer_cat_impl).
    if count == 0
        || count > MAX_FRAMES
        || count * samples_per_frame(toc, SampleRate::Hz48000) > MAX_PACKET_SAMPLES
    {
        return Err(Error::BAD_ARG);
    }
    let mut sizes = [0u16; MAX_FRAMES];
    for (size, frame) in sizes.iter_mut().zip(frames) {
        if frame.len() > MAX_FRAME_BYTES {
            return Err(Error::BAD_ARG);
        }
        *size = frame.len() as u16;
    }
    Ok(sizes)
}

/// Copies `frames` one after the other into `out` from offset `at`.
fn copy_frames(frames: &[&[u8]], out: &mut [u8], at: usize) {
    let mut pos = at;
    for frame in frames {
        out[pos..pos + frame.len()].copy_from_slice(frame);
        pos += frame.len();
    }
}

/// Write one packet made of `frames`: libopus
/// `opus_repacketizer_out_range_impl` (repacketizer.c) without extensions.
///
/// - `toc` supplies the configuration and the stereo flag; its frame-count
///   code is replaced by the one that fits the frames.
/// - [`Framing::SelfDelimited`] adds the size of the last frame.
/// - [`Padding::FillBuffer`] fills `out` to its full length with padding.
///   The packet then is exactly `out.len()` bytes long.
///
/// Returns the number of bytes written. [`Repacketizer`] does the same for
/// the frames of whole packets, and carries their extensions.
///
/// Errors: [`BadArg`](crate::ErrorKind::BadArg) when there are no frames,
/// more than 120 ms of them, or a frame of more than 1275 bytes;
/// [`BufferTooSmall`](crate::ErrorKind::BufferTooSmall) when the packet
/// does not fit in `out`.
pub fn write(
    toc: u8,
    frames: &[&[u8]],
    out: &mut [u8],
    framing: Framing,
    padding: Padding,
) -> Result<usize, Error> {
    let sizes = frame_sizes(toc, frames)?;
    let sizes = &sizes[..frames.len()];
    emit(toc, sizes, out, framing.is_self_delimited(), padding.fills_buffer(), &[], |out, at| {
        copy_frames(frames, out, at)
    })
}

/// Joins the frames of Opus packets into new packets, and splits packets
/// into their frames: libopus `OpusRepacketizer` (repacketizer.c).
///
/// [`cat`](Self::cat) adds the frames of a packet. All packets must have
/// the same TOC byte apart from the frame-count code (the same mode,
/// bandwidth, frame duration and channel count), and together at most
/// 120 ms. [`out_range`](Self::out_range) writes a packet of some of the
/// frames, [`out`](Self::out) one of all of them.
///
/// The extensions in the padding of the packets go into the new packets,
/// with their frame numbers adjusted, when the frame they start from is
/// part of the new packet. Other padding is dropped.
///
/// The repacketizer borrows the packets; it copies nothing until a packet
/// is written. libopus's `opus_repacketizer_init` is [`reset`](Self::reset).
#[derive(Clone)]
pub struct Repacketizer<'a> {
    toc: u8,
    nb_frames: usize,
    frames: [&'a [u8]; MAX_FRAMES],
    /// The padding of each packet, at the place of its first frame; empty
    /// at the other frames.
    paddings: [&'a [u8]; MAX_FRAMES],
    /// The number of frames of the packet each padding belongs to.
    padding_nb_frames: [u8; MAX_FRAMES],
}

impl core::fmt::Debug for Repacketizer<'_> {
    /// The TOC byte and the number of frames added so far. The bytes of
    /// the frames and their padding are left out.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Repacketizer")
            .field("toc", &self.toc)
            .field("nb_frames", &self.nb_frames)
            .finish_non_exhaustive()
    }
}

impl Default for Repacketizer<'_> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> Repacketizer<'a> {
    /// An empty repacketizer.
    pub const fn new() -> Self {
        Repacketizer {
            toc: 0,
            nb_frames: 0,
            frames: [&[]; MAX_FRAMES],
            paddings: [&[]; MAX_FRAMES],
            padding_nb_frames: [0; MAX_FRAMES],
        }
    }

    /// Removes all frames. libopus `opus_repacketizer_init`.
    pub fn reset(&mut self) {
        self.nb_frames = 0;
    }

    /// The number of frames added so far. libopus
    /// `opus_repacketizer_get_nb_frames`.
    pub fn nb_frames(&self) -> usize {
        self.nb_frames
    }

    /// Adds the frames of the packet `data`. libopus `opus_repacketizer_cat`.
    ///
    /// Fails with [`InvalidPacket`](crate::ErrorKind::InvalidPacket), and adds
    /// nothing, when the packet is not valid, its TOC byte does not match that
    /// of the frames already added (apart from the frame-count code), or the
    /// frames would last more than 120 ms.
    ///
    /// libopus implements it in `opus_repacketizer_cat_impl`, which also
    /// takes self-delimited packets for `opus_multistream_packet_unpad`.
    /// This crate's `multistream_unpad` parses those itself.
    pub fn cat(&mut self, data: &'a [u8]) -> Result<(), Error> {
        let Some(&toc) = data.first() else {
            return Err(Error::INVALID_PACKET);
        };
        if self.nb_frames == 0 {
            self.toc = toc;
        } else if (self.toc & 0xFC) != (toc & 0xFC) {
            return Err(Error::INVALID_PACKET);
        }
        let curr_nb_frames = nb_frames(data)?;
        if curr_nb_frames < 1 {
            return Err(Error::INVALID_PACKET);
        }
        // At most 120 ms: 960 samples at 8 kHz.
        if (curr_nb_frames + self.nb_frames) * samples_per_frame(self.toc, SampleRate::Hz8000) > 960 {
            return Err(Error::INVALID_PACKET);
        }
        let packet = parse(data, Framing::Normal)?;
        let n = self.nb_frames;
        for (k, frame) in packet.frames(data).enumerate() {
            self.frames[n + k] = frame;
            self.paddings[n + k] = &[];
            self.padding_nb_frames[n + k] = 0;
        }
        self.paddings[n] = packet.padding(data);
        self.padding_nb_frames[n] = packet.count as u8;
        self.nb_frames += packet.count;
        Ok(())
    }

    /// Writes a packet of frames `begin..end` into `out`, whose length is
    /// the largest packet allowed. Returns its length. libopus
    /// `opus_repacketizer_out_range`.
    ///
    /// The extensions in the padding of the packets in the range are kept.
    /// Their frame numbers then count from frame `begin`. The extensions of
    /// a packet whose first frame is outside the range are dropped.
    ///
    /// Errors:
    /// - [`BadArg`](crate::ErrorKind::BadArg) when the range is empty or goes
    ///   past the last frame. Also when a packet in the range has an
    ///   extension for one of its frames at or after `end`, as in libopus.
    /// - [`BufferTooSmall`](crate::ErrorKind::BufferTooSmall) when the packet
    ///   does not fit in `out`.
    /// - [`InternalError`](crate::ErrorKind::InternalError) when the padding
    ///   of a packet in the range holds invalid extensions.
    /// - [`AllocFail`](crate::ErrorKind::AllocFail) without the feature
    ///   `alloc`, when the packets in the range hold more than 32 extensions.
    pub fn out_range(&self, begin: usize, end: usize, out: &mut [u8]) -> Result<usize, Error> {
        self.out_range_ext(begin, end, out, Framing::Normal, Padding::Shortest, &[])
    }

    /// Writes a packet of all frames into `out`. libopus
    /// `opus_repacketizer_out`.
    ///
    /// Errors: [`BadArg`](crate::ErrorKind::BadArg) when no frame was added,
    /// and otherwise those of [`out_range`](Self::out_range):
    /// [`BufferTooSmall`](crate::ErrorKind::BufferTooSmall),
    /// [`InternalError`](crate::ErrorKind::InternalError) and, without the
    /// feature `alloc`, [`AllocFail`](crate::ErrorKind::AllocFail).
    pub fn out(&self, out: &mut [u8]) -> Result<usize, Error> {
        self.out_range_ext(0, self.nb_frames, out, Framing::Normal, Padding::Shortest, &[])
    }

    /// [`out_range`](Self::out_range) with the options of libopus's
    /// internal `opus_repacketizer_out_range_impl`:
    ///
    /// - [`Framing::SelfDelimited`] adds the size of the last frame (RFC 6716
    ///   appendix B), as every stream but the last of a multistream packet
    ///   needs.
    /// - [`Padding::FillBuffer`] makes the packet exactly `out.len()` bytes
    ///   long.
    /// - `extensions` are added before those of the packets' padding. Their
    ///   frame numbers count from frame `begin`.
    ///
    /// Besides the errors of `out_range`, the extensions give the errors of
    /// [`extensions::generate`].
    ///
    /// Up to 32 extensions in all, `extensions` and those of the padding, need
    /// no allocation. More need the feature `alloc`; without it they give
    /// [`AllocFail`](crate::ErrorKind::AllocFail).
    pub fn out_range_ext(
        &self,
        begin: usize,
        end: usize,
        out: &mut [u8],
        framing: Framing,
        padding: Padding,
        extensions: &[Extension],
    ) -> Result<usize, Error> {
        let (self_delimited, pad) = (framing.is_self_delimited(), padding.fills_buffer());
        if begin >= end || end > self.nb_frames {
            return Err(Error::BAD_ARG);
        }
        let frames = &self.frames[begin..end];
        let mut sizes = [0u16; MAX_FRAMES];
        for (size, frame) in sizes.iter_mut().zip(frames) {
            *size = frame.len() as u16;
        }
        let sizes = &sizes[..frames.len()];
        // The extensions in the padding of the packets.
        let mut found = 0;
        for i in begin..end {
            found += extensions::count_checked(self.paddings[i], self.padding_nb_frames[i] as usize)
                .map_err(|_| Error::INTERNAL_ERROR)?;
        }
        let place = |out: &mut [u8], at: usize| copy_frames(frames, out, at);
        if found == 0 {
            return emit(self.toc, sizes, out, self_delimited, pad, extensions, place);
        }
        let mut all = ExtensionList::with_capacity(extensions.len() + found)?;
        for &ext in extensions {
            all.push(ext);
        }
        for i in begin..end {
            let iter = ExtensionIterator::new(self.paddings[i], self.padding_nb_frames[i] as usize);
            for mut ext in iter.map_while(Result::ok) {
                ext.frame += i - begin;
                all.push(ext);
            }
        }
        emit(self.toc, sizes, out, self_delimited, pad, all.as_slice(), place)
    }
}

/// Pad the packet `data[..len]` in place to `new_len` bytes: libopus
/// `opus_packet_pad` (repacketizer.c).
///
/// The result is a code 3 packet whose padding holds the extensions the
/// packet had, then zeros when it had none, unless one more byte is all
/// that is needed. `data` must hold at least `new_len` bytes. When `len`
/// equals `new_len`, the packet stays as it is and is not read, as in
/// libopus.
///
/// Errors: [`BadArg`](crate::ErrorKind::BadArg) when `len` is 0, `new_len` is
/// below `len` or `data` is shorter than either;
/// [`InvalidPacket`](crate::ErrorKind::InvalidPacket) when the packet is not
/// valid; [`InternalError`](crate::ErrorKind::InternalError) when the padding
/// of the packet holds invalid extensions;
/// [`AllocFail`](crate::ErrorKind::AllocFail) without the feature `alloc`,
/// when the padding of the packet holds more than 32 extensions, or holds
/// extensions and is longer than 1275 bytes.
pub fn pad(data: &mut [u8], len: usize, new_len: usize) -> Result<(), Error> {
    pad_with_extensions(data, len, new_len, Padding::FillBuffer, &[]).map(|_| ())
}

/// libopus's internal `opus_packet_pad_impl`: rewrites the packet
/// `data[..len]` in place, in at most `new_len` bytes, with `extensions`
/// added before the extensions it has. With [`Padding::FillBuffer`] the
/// packet takes exactly `new_len` bytes. Returns the new length of the
/// packet.
///
/// When `len == new_len` and `extensions` is empty, there is nothing to
/// do: the packet stays as it is, and the result is `len`. When
/// `extensions` is not empty, they are always written, also when
/// `len == new_len`; if they do not fit in `new_len` bytes, the result is
/// an error of kind [`BufferTooSmall`](crate::ErrorKind::BufferTooSmall).
/// (libopus returns `OPUS_OK` when `len == new_len` and leaves the
/// extensions out; its only caller never gets there.)
///
/// The frame numbers of `extensions` count the frames of this packet.
/// Besides the errors of [`pad`], the extensions give those of
/// [`extensions::generate`].
///
/// Without the feature `alloc`, a packet whose padding already holds extensions
/// can only be rewritten when that padding is at most 1275 bytes and the
/// extensions are at most 32 in all; otherwise the result is
/// [`AllocFail`](crate::ErrorKind::AllocFail).
pub fn pad_with_extensions(
    data: &mut [u8],
    len: usize,
    new_len: usize,
    padding: Padding,
    extensions: &[Extension],
) -> Result<usize, Error> {
    let pad = padding.fills_buffer();
    if len < 1 || len > data.len() {
        return Err(Error::BAD_ARG);
    }
    // libopus returns here whether there are extensions or not, without
    // reading the packet. Extensions go on below, so that they are written
    // or the call fails.
    if len == new_len && extensions.is_empty() {
        return Ok(len);
    }
    if len > new_len || new_len > data.len() {
        return Err(Error::BAD_ARG);
    }
    // The checks of opus_repacketizer_cat: `parse` makes the same ones.
    let packet = parse(&data[..len], Framing::Normal)?;
    let found = extensions::count_checked(packet.padding(&data[..len]), packet.count).map_err(|_| Error::INTERNAL_ERROR)?;
    if found == 0 {
        return pad_in_place(data, new_len, &packet, pad, extensions);
    }
    pad_keeping_extensions(data, new_len, &packet, pad, extensions, found)
}

/// Rewrites the packet `packet` of `data` into `data[..new_len]` with the
/// extensions `extensions` only.
fn pad_in_place(
    data: &mut [u8],
    new_len: usize,
    packet: &ParsedPacket,
    pad: bool,
    extensions: &[Extension],
) -> Result<usize, Error> {
    let sizes = &packet.sizes[..packet.count];
    let start = packet.payload_offset;
    let payload: usize = sizes.iter().map(|&s| s as usize).sum();
    // libopus copies the packet and writes the new one over the old. Here
    // the frames, which are one block of bytes, move to their new place
    // first. The new header is built from the parsed sizes alone, so it can
    // overwrite what is left of the old one.
    emit(packet.toc, sizes, &mut data[..new_len], false, pad, extensions, |out, at| {
        out.copy_within(start..start + payload, at)
    })
}

/// The most bytes of padding with extensions that `pad_keeping_extensions`
/// copies on the stack. A longer padding needs the feature `alloc`.
const PADDING_COPY: usize = MAX_FRAME_BYTES;

/// `pad_in_place` for a packet whose padding holds `found` extensions:
/// they go into the new padding after `extensions`. They are read from a
/// copy of the old padding, which the new packet may overwrite.
#[inline(never)]
fn pad_keeping_extensions(
    data: &mut [u8],
    new_len: usize,
    packet: &ParsedPacket,
    pad: bool,
    extensions: &[Extension],
    found: usize,
) -> Result<usize, Error> {
    let old = packet.padding(data);
    // A padding of up to `PADDING_COPY` (1,275) bytes is copied to the
    // stack. A longer one, which is rare, is copied to the heap.
    let mut buf: FixedVec<u8, PADDING_COPY> = FixedVec::new();
    #[cfg(feature = "alloc")]
    let owned;
    let copy: &[u8] = if old.len() <= PADDING_COPY {
        buf.extend_from_slice(old);
        &buf
    } else {
        #[cfg(feature = "alloc")]
        {
            owned = old.to_vec();
            &owned
        }
        #[cfg(not(feature = "alloc"))]
        return Err(Error::new(
            crate::ErrorKind::AllocFail,
            "more than 1275 bytes of padding need the alloc feature",
        ));
    };
    let mut all = ExtensionList::with_capacity(extensions.len() + found)?;
    for &ext in extensions {
        all.push(ext);
    }
    for ext in ExtensionIterator::new(copy, packet.count).map_while(Result::ok) {
        all.push(ext);
    }
    pad_in_place(data, new_len, packet, pad, all.as_slice())
}

/// Remove the padding and the extensions of the packet `data[..len]` in
/// place, and write it in its shortest form. Returns the new length.
/// libopus `opus_packet_unpad` (repacketizer.c).
///
/// Errors: [`BadArg`](crate::ErrorKind::BadArg) when `len` is 0 or above
/// `data.len()`, and [`InvalidPacket`](crate::ErrorKind::InvalidPacket) when
/// the packet is not valid.
pub fn unpad(data: &mut [u8], len: usize) -> Result<usize, Error> {
    if len < 1 || len > data.len() {
        return Err(Error::BAD_ARG);
    }
    let packet = parse(&data[..len], Framing::Normal)?;
    pad_in_place(data, len, &packet, false, &[])
}

/// Pad the multistream packet `data[..len]` of `nb_streams` streams in place
/// to `new_len` bytes: libopus `opus_multistream_packet_pad`
/// (repacketizer.c). The padding goes into the last stream, which keeps its
/// extensions as with [`pad`].
///
/// Errors: [`BadArg`](crate::ErrorKind::BadArg) when `len` is 0, `new_len`
/// is below `len` or `data` is shorter than either;
/// [`InvalidPacket`](crate::ErrorKind::InvalidPacket) when a stream is not
/// valid; and the errors of [`pad`] for the last stream, among them
/// [`AllocFail`](crate::ErrorKind::AllocFail) without the feature `alloc`.
pub fn multistream_pad(
    data: &mut [u8],
    len: usize,
    new_len: usize,
    nb_streams: usize,
) -> Result<(), Error> {
    if len < 1 || len > data.len() {
        return Err(Error::BAD_ARG);
    }
    if len == new_len {
        return Ok(());
    }
    if len > new_len || new_len > data.len() {
        return Err(Error::BAD_ARG);
    }
    let amount = new_len - len;
    // Seek to the last stream.
    let mut start = 0usize;
    for _ in 1..nb_streams {
        if start >= len {
            return Err(Error::INVALID_PACKET);
        }
        start += parse(&data[start..len], Framing::SelfDelimited)?.packet_offset;
    }
    let last_len = len.checked_sub(start).ok_or(Error::INVALID_PACKET)?;
    pad(&mut data[start..], last_len, last_len + amount)
}

/// Remove the padding and the extensions of every stream of the
/// multistream packet `data[..len]` of `nb_streams` streams, in place.
/// Returns the new length. libopus `opus_multistream_packet_unpad`
/// (repacketizer.c).
///
/// The streams are rewritten one after the other. When a stream is not
/// valid, the function returns an error and the streams before it stay
/// rewritten, as in libopus.
pub fn multistream_unpad(data: &mut [u8], len: usize, nb_streams: usize) -> Result<usize, Error> {
    if len < 1 || len > data.len() {
        return Err(Error::BAD_ARG);
    }
    let mut src = 0usize;
    let mut dst = 0usize;
    for s in 0..nb_streams {
        let self_delimited = s != nb_streams - 1;
        if src >= len {
            return Err(Error::INVALID_PACKET);
        }
        // The parse makes every check of libopus's opus_repacketizer_cat_impl
        // on a fresh repacketizer: at least one frame, at most 120 ms, and
        // the same parse of the stream. libopus copies the frames into a
        // repacketizer to write them out; here they move in place.
        let packet = parse(&data[src..len], Framing::from_flag(self_delimited))?;
        let sizes = &packet.sizes[..packet.count];
        let start = src - dst + packet.payload_offset;
        let payload: usize = sizes.iter().map(|&s| s as usize).sum();
        // The stream moves to `dst`, which is never after `src`; the output
        // is never longer than the input, so the room left is enough.
        let written = emit(packet.toc, sizes, &mut data[dst..len], self_delimited, false, &[], |out, at| {
            out.copy_within(start..start + payload, at)
        })?;
        dst += written;
        src += packet.packet_offset;
    }
    Ok(dst)
}

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

    /// TOC byte of a CELT-only fullband 20 ms mono packet.
    const TOC_CELT_20: u8 = 0xF8;
    /// TOC byte of a CELT-only fullband 2.5 ms mono packet.
    const TOC_CELT_2_5: u8 = 0xE0;

    #[test]
    fn samples_per_frame_covers_every_configuration() {
        // SILK-only narrowband: 10, 20, 40, 60 ms.
        assert_eq!(samples_per_frame(0x00, SampleRate::Hz48000), 480);
        assert_eq!(samples_per_frame(0x08, SampleRate::Hz48000), 960);
        assert_eq!(samples_per_frame(0x10, SampleRate::Hz48000), 1920);
        assert_eq!(samples_per_frame(0x18, SampleRate::Hz48000), 2880);
        // Hybrid: 10 and 20 ms.
        assert_eq!(samples_per_frame(0x60, SampleRate::Hz16000), 160);
        assert_eq!(samples_per_frame(0x68, SampleRate::Hz16000), 320);
        // CELT-only: 2.5, 5, 10, 20 ms.
        assert_eq!(samples_per_frame(0x80, SampleRate::Hz8000), 20);
        assert_eq!(samples_per_frame(0x88, SampleRate::Hz8000), 40);
        assert_eq!(samples_per_frame(0x90, SampleRate::Hz8000), 80);
        assert_eq!(samples_per_frame(0x98, SampleRate::Hz8000), 160);
    }

    #[test]
    fn code_0_is_one_frame_to_the_end() {
        let p = parse(&[TOC_CELT_20, 1, 2, 3], Framing::Normal).unwrap();
        assert_eq!((p.count, p.sizes[0], p.payload_offset, p.packet_offset), (1, 3, 1, 4));
        // A TOC byte alone is one empty frame.
        let p = parse(&[TOC_CELT_20], Framing::Normal).unwrap();
        assert_eq!((p.count, p.sizes[0], p.packet_offset), (1, 0, 1));
        assert!(parse(&[], Framing::Normal).is_err());
    }

    #[test]
    fn code_1_needs_an_even_payload() {
        let p = parse(&[TOC_CELT_20 | 1, 1, 2, 3, 4], Framing::Normal).unwrap();
        assert_eq!((p.count, p.sizes[0], p.sizes[1]), (2, 2, 2));
        assert_eq!(p.frame(&[TOC_CELT_20 | 1, 1, 2, 3, 4], 1), &[3, 4]);
        assert!(parse(&[TOC_CELT_20 | 1, 1, 2, 3], Framing::Normal).is_err());
    }

    #[test]
    fn code_2_reads_the_first_size() {
        let data = [TOC_CELT_20 | 2, 1, 9, 8, 7];
        let p = parse(&data, Framing::Normal).unwrap();
        assert_eq!((p.count, p.sizes[0], p.sizes[1], p.payload_offset), (2, 1, 2, 2));
        let frames: Vec<&[u8]> = p.frames(&data).collect();
        assert_eq!(frames, [&[9u8][..], &[8, 7][..]]);
        // The first size runs past the end.
        assert!(parse(&[TOC_CELT_20 | 2, 4, 9, 8, 7], Framing::Normal).is_err());
        // The size field is missing.
        assert!(parse(&[TOC_CELT_20 | 2], Framing::Normal).is_err());
    }

    #[test]
    fn code_3_checks_count_duration_and_padding() {
        // No frames.
        assert!(parse(&[TOC_CELT_20 | 3, 0], Framing::Normal).is_err());
        // 7 frames of 20 ms are more than 120 ms.
        assert!(parse(&[TOC_CELT_20 | 3, 7], Framing::Normal).is_err());
        // 48 frames of 2.5 ms are exactly 120 ms.
        assert_eq!(parse(&[TOC_CELT_2_5 | 3, 48], Framing::Normal).unwrap().count, 48);
        assert!(parse(&[TOC_CELT_2_5 | 3, 49], Framing::Normal).is_err());
        // CBR: the payload must divide by the count.
        assert!(parse(&[TOC_CELT_20 | 3, 2, 1, 2, 3], Framing::Normal).is_err());
        // Padding: 2 bytes at the end are not part of a frame.
        let p = parse(&[TOC_CELT_20 | 3, 0x41, 2, 7, 0, 0], Framing::Normal).unwrap();
        assert_eq!((p.count, p.sizes[0], p.padding_len, p.packet_offset), (1, 1, 2, 6));
        // Padding longer than the packet.
        assert!(parse(&[TOC_CELT_20 | 3, 0x41, 9, 7], Framing::Normal).is_err());
        // The padding flag without a length byte.
        assert!(parse(&[TOC_CELT_20 | 3, 0x41], Framing::Normal).is_err());
    }

    #[test]
    fn self_delimited_packet_ends_before_the_next_stream() {
        // Code 0, size 2, then 3 bytes of another stream.
        let data = [TOC_CELT_20, 2, 5, 6, 0xAA, 0xBB, 0xCC];
        let p = parse(&data, Framing::SelfDelimited).unwrap();
        assert_eq!((p.count, p.sizes[0], p.payload_offset, p.packet_offset), (1, 2, 2, 4));
        // Code 1: the one size applies to both frames.
        let data = [TOC_CELT_20 | 1, 2, 5, 6, 7, 8, 0xAA];
        let p = parse(&data, Framing::SelfDelimited).unwrap();
        assert_eq!((p.count, p.sizes[0], p.sizes[1], p.packet_offset), (2, 2, 2, 6));
        // The size does not fit.
        assert!(parse(&[TOC_CELT_20, 3, 5, 6], Framing::SelfDelimited).is_err());
        assert!(parse(&[TOC_CELT_20 | 1, 2, 5, 6, 7], Framing::SelfDelimited).is_err());
    }

    #[test]
    fn a_frame_may_not_exceed_1275_bytes() {
        let mut data = vec![0u8; 1 + 1276];
        data[0] = TOC_CELT_20;
        assert!(parse(&data, Framing::Normal).is_err());
        assert_eq!(parse(&data[..1276], Framing::Normal).unwrap().sizes[0], 1275);
    }

    #[test]
    fn write_picks_the_frame_count_code() {
        let mut out = [0u8; 64];
        let a = [1u8, 2, 3];
        let b = [4u8, 5, 6];
        let c = [7u8];
        // One frame: code 0.
        let n = write(TOC_CELT_20 | 3, &[&a], &mut out, Framing::Normal, Padding::Shortest).unwrap();
        assert_eq!(&out[..n], &[TOC_CELT_20, 1, 2, 3]);
        // Two frames of one size: code 1.
        let n = write(TOC_CELT_20, &[&a, &b], &mut out, Framing::Normal, Padding::Shortest).unwrap();
        assert_eq!(&out[..n], &[TOC_CELT_20 | 1, 1, 2, 3, 4, 5, 6]);
        // Two frames of different sizes: code 2.
        let n = write(TOC_CELT_20, &[&a, &c], &mut out, Framing::Normal, Padding::Shortest).unwrap();
        assert_eq!(&out[..n], &[TOC_CELT_20 | 2, 3, 1, 2, 3, 7]);
        // Three frames of one size: code 3, CBR.
        let n = write(TOC_CELT_20, &[&a, &b, &a], &mut out, Framing::Normal, Padding::Shortest).unwrap();
        assert_eq!(&out[..n], &[TOC_CELT_20 | 3, 3, 1, 2, 3, 4, 5, 6, 1, 2, 3]);
        // Three frames of different sizes: code 3, VBR.
        let n = write(TOC_CELT_20, &[&a, &c, &b], &mut out, Framing::Normal, Padding::Shortest).unwrap();
        assert_eq!(&out[..n], &[TOC_CELT_20 | 3, 0x83, 3, 1, 1, 2, 3, 7, 4, 5, 6]);
    }

    #[test]
    fn write_self_delimited_adds_the_last_size() {
        let mut out = [0u8; 16];
        let n = write(TOC_CELT_20, &[&[9, 9]], &mut out, Framing::SelfDelimited, Padding::Shortest).unwrap();
        assert_eq!(&out[..n], &[TOC_CELT_20, 2, 9, 9]);
        let p = parse(&out[..n], Framing::SelfDelimited).unwrap();
        assert_eq!((p.count, p.sizes[0], p.packet_offset), (1, 2, n));
    }

    #[test]
    fn write_pads_to_the_exact_length() {
        let frame = [5u8; 4];
        // One byte short of the buffer: code 3 without padding.
        let mut out = [0xEEu8; 6];
        assert_eq!(write(TOC_CELT_20, &[&frame], &mut out, Framing::Normal, Padding::FillBuffer), Ok(6));
        assert_eq!(out, [TOC_CELT_20 | 3, 1, 5, 5, 5, 5]);
        // The buffer fits exactly: the packet stays code 0.
        let mut out = [0xEEu8; 5];
        assert_eq!(write(TOC_CELT_20, &[&frame], &mut out, Framing::Normal, Padding::FillBuffer), Ok(5));
        assert_eq!(out, [TOC_CELT_20, 5, 5, 5, 5]);
        // More room: a length byte and zeros.
        let mut out = [0xEEu8; 10];
        assert_eq!(write(TOC_CELT_20, &[&frame], &mut out, Framing::Normal, Padding::FillBuffer), Ok(10));
        assert_eq!(out, [TOC_CELT_20 | 3, 0x41, 3, 5, 5, 5, 5, 0, 0, 0]);
        let p = parse(&out, Framing::Normal).unwrap();
        assert_eq!((p.count, p.sizes[0], p.padding_len), (1, 4, 3));
    }

    #[test]
    fn write_rejects_bad_input_without_panicking() {
        let mut out = [0u8; 8];
        assert!(write(TOC_CELT_20, &[], &mut out, Framing::Normal, Padding::Shortest).is_err());
        assert!(write(TOC_CELT_20, &[&[0; 9]], &mut out, Framing::Normal, Padding::Shortest).is_err());
        assert!(write(TOC_CELT_20, &[&[0; 1276]], &mut [0u8; 2000], Framing::Normal, Padding::Shortest).is_err());
        // 7 frames of 20 ms are more than 120 ms.
        let f: &[u8] = &[1];
        assert!(write(TOC_CELT_20, &[f; 7], &mut [0u8; 64], Framing::Normal, Padding::Shortest).is_err());
        assert!(write(TOC_CELT_20, &[f], &mut [], Framing::Normal, Padding::Shortest).is_err());
    }

    #[test]
    fn pad_moves_the_frames_in_place() {
        let mut data = [TOC_CELT_20 | 2, 1, 9, 8, 7, 0, 0, 0, 0, 0];
        pad(&mut data, 5, 10).unwrap();
        // Code 3, VBR, 2 frames, padding: 1 length byte and 3 zeros.
        assert_eq!(data, [TOC_CELT_20 | 3, 0xC2, 3, 1, 9, 8, 7, 0, 0, 0]);
        let p = parse(&data, Framing::Normal).unwrap();
        assert_eq!((p.count, p.sizes[0], p.sizes[1], p.padding_len), (2, 1, 2, 3));
        // Nothing to do, and arguments that make no sense.
        assert_eq!(pad(&mut data, 10, 10), Ok(()));
        assert!(pad(&mut data, 10, 9).is_err());
        assert!(pad(&mut data, 0, 5).is_err());
        assert!(pad(&mut data, 5, 11).is_err());
        // With `len == new_len`, as in libopus, the packet is not read.
        assert_eq!(pad(&mut [0xFF], 1, 1), Ok(()));
    }

    #[test]
    fn pad_with_extensions_writes_the_extensions_or_fails() {
        let ext = [Extension::new(5, 0, &[1])];
        // A CELT packet of one frame of 3 bytes. With the extension (2
        // bytes) it is a code 3 packet of 8 bytes: TOC, frame count,
        // padding length, the frame and the extension.
        let plain = [TOC_CELT_20, 1, 2, 3];
        // Nothing to do: the packet keeps its length.
        let mut data = plain;
        for padding in [Padding::Shortest, Padding::FillBuffer] {
            assert_eq!(pad_with_extensions(&mut data, 4, 4, padding, &[]), Ok(4));
            assert_eq!(data, plain);
        }
        // Too little room is an error, also when `len == new_len`. libopus
        // returns OPUS_OK when `len == new_len` and drops the extension.
        for new_len in [4, 5, 7] {
            let mut data = [0u8; 8];
            data[..4].copy_from_slice(&plain);
            let err = pad_with_extensions(&mut data, 4, new_len, Padding::Shortest, &ext).unwrap_err();
            assert_eq!(err.kind(), crate::ErrorKind::BufferTooSmall, "new_len {new_len}");
        }
        let mut data = [0u8; 8];
        data[..4].copy_from_slice(&plain);
        assert_eq!(pad_with_extensions(&mut data, 4, 8, Padding::Shortest, &ext), Ok(8));
        let p = parse(&data, Framing::Normal).unwrap();
        let mut found = [Extension::default(); 2];
        assert_eq!(extensions::parse(p.padding(&data), &mut found, p.nb_frames()), Ok(1));
        assert_eq!(found[0], ext[0]);
        // A packet whose padding has room for the extension takes it
        // without growing, also when `len == new_len`.
        for (padding, want) in [(Padding::Shortest, 8), (Padding::FillBuffer, 12)] {
            let mut data = [0u8; 12];
            data[..4].copy_from_slice(&plain);
            pad(&mut data, 4, 12).unwrap();
            assert_eq!(pad_with_extensions(&mut data, 12, 12, padding, &ext), Ok(want));
            let p = parse(&data[..want], Framing::Normal).unwrap();
            assert!(p.frames(&data[..want]).eq([&plain[1..]]));
            let mut found = [Extension::default(); 2];
            assert_eq!(extensions::parse(p.padding(&data[..want]), &mut found, 1), Ok(1));
            assert_eq!(found[0], ext[0]);
        }
    }

    #[test]
    fn multistream_validate_wants_equal_durations() {
        // Stream 0: self-delimited 20 ms. Stream 1: 20 ms.
        let ok = [TOC_CELT_20, 1, 7, TOC_CELT_20, 8, 9];
        assert_eq!(multistream_validate(&ok, 2, SampleRate::Hz48000), Ok(960));
        // Stream 1 is 2.5 ms.
        let bad = [TOC_CELT_20, 1, 7, TOC_CELT_2_5, 8, 9];
        assert!(multistream_validate(&bad, 2, SampleRate::Hz48000).is_err());
        // The second stream is missing.
        assert!(multistream_validate(&[TOC_CELT_20, 1, 7], 2, SampleRate::Hz48000).is_err());
        assert!(multistream_validate(&ok, 0, SampleRate::Hz48000).is_err());
    }

    #[test]
    fn multistream_pad_pads_the_last_stream() {
        let mut data = [TOC_CELT_20, 1, 7, TOC_CELT_20, 8, 9, 0, 0, 0];
        multistream_pad(&mut data, 6, 9, 2).unwrap();
        assert_eq!(data, [TOC_CELT_20, 1, 7, TOC_CELT_20 | 3, 0x41, 1, 8, 9, 0]);
        assert_eq!(multistream_validate(&data, 2, SampleRate::Hz48000), Ok(960));
    }

    #[test]
    fn bandwidth_and_channels_of_every_toc_byte() {
        // RFC 6716 table 2: the bandwidth of each configuration.
        let expected = |config: u8| match config {
            0..=3 | 16..=19 => Bandwidth::Narrowband,
            4..=7 => Bandwidth::Mediumband,
            8..=11 | 20..=23 => Bandwidth::Wideband,
            12..=13 | 24..=27 => Bandwidth::Superwideband,
            _ => Bandwidth::Fullband,
        };
        for toc in 0..=255u8 {
            assert_eq!(bandwidth(toc), expected(toc >> 3), "TOC {toc:#04x}");
            let channels = if toc & 0x04 != 0 { Channels::Stereo } else { Channels::Mono };
            assert_eq!(nb_channels(toc), channels, "TOC {toc:#04x}");
        }
    }

    #[test]
    fn parsed_packet_methods_give_what_parse_found() {
        // Code 3, VBR, padding, 3 frames of 1, 2 and 1 bytes, 2 bytes of
        // padding.
        let data = [TOC_CELT_20 | 3, 0xC3, 2, 1, 2, 9, 8, 7, 6, 0, 0];
        let p = parse(&data, Framing::Normal).unwrap();
        assert_eq!(p.toc(), TOC_CELT_20 | 3);
        assert_eq!(p.nb_frames(), 3);
        assert_eq!(p.frame_sizes(), &[1, 2, 1]);
        assert_eq!((p.payload_offset(), p.packet_offset(), p.padding_len()), (5, 11, 2));
        let frames: Vec<&[u8]> = p.frames(&data).collect();
        assert_eq!(frames, [&[9u8][..], &[8, 7][..], &[6][..]]);
        assert_eq!(p.padding(&data), &[0, 0]);
        // Self-delimited: the packet ends before the data that follows.
        let data = [TOC_CELT_20 | 4, 2, 5, 6, 0xAA];
        let p = parse(&data, Framing::SelfDelimited).unwrap();
        assert_eq!((p.toc(), p.nb_frames(), p.frame_sizes()), (TOC_CELT_20 | 4, 1, &[2u16][..]));
        assert_eq!((p.payload_offset(), p.packet_offset(), p.padding_len()), (2, 4, 0));
        assert_eq!(nb_channels(p.toc()), Channels::Stereo);
        // The same bytes as an ordinary packet: one frame of 4 bytes.
        let p = parse(&data, Framing::Normal).unwrap();
        assert_eq!((p.frame_sizes(), p.payload_offset(), p.packet_offset()), (&[4u16][..], 1, 5));
    }

    #[test]
    fn parsed_packet_with_other_data_gives_empty_slices() {
        let data = [TOC_CELT_20 | 3, 0xC3, 2, 1, 2, 9, 8, 7, 6, 0, 0];
        let p = parse(&data, Framing::Normal).unwrap();
        for short in [&data[..0], &data[..3], &data[..5]] {
            assert_eq!(p.frames(short).count(), 3);
            assert!(p.frames(short).all(|f| f.is_empty()));
            assert_eq!(p.frame(short, 2), &[] as &[u8]);
            assert_eq!(p.padding(short), &[] as &[u8]);
        }
        // The frames fit in 10 bytes, the padding does not.
        let cut = &data[..10];
        assert_eq!(p.frame(cut, 2), &[6]);
        assert_eq!(p.padding(cut), &[] as &[u8]);
        assert_eq!(p.frame(&data, 3), &[] as &[u8]);
        assert_eq!(p.frame(&data, usize::MAX), &[] as &[u8]);
    }

    #[test]
    fn framing_and_padding_follow_the_libopus_flags() {
        assert_eq!(Framing::from_flag(false), Framing::Normal);
        assert_eq!(Framing::from_flag(true), Framing::SelfDelimited);
        assert!(Framing::SelfDelimited.is_self_delimited() && !Framing::Normal.is_self_delimited());
        assert_eq!(Padding::from_flag(false), Padding::Shortest);
        assert_eq!(Padding::from_flag(true), Padding::FillBuffer);
        assert!(Padding::FillBuffer.fills_buffer() && !Padding::Shortest.fills_buffer());
    }
}