rtmp-runtime 0.13.1

Sans-IO RTMP 1.0 (Adobe Real-Time Messaging Protocol) publish engine for both ends: a driveable ingest server state machine and a publish client over the handshake, chunk stream, AMF0, and message layers; optional tokio socket adapter.
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
//! FLV tag-body syntax — Adobe Flash Video File Format Specification v10.1
//! Annex E §E.4.2 (`AudioTagHeader` + `AACAUDIODATA`) and §E.4.3
//! (`VideoTagHeader` + `AVCVIDEOPACKET`) — and the script-data tag's
//! `onMetaData` body (§E.4.1).
//!
//! The tag *framing* (file header, tag header, `PreviousTagSize`) is
//! [`crate::flv`]'s; this module is what that framing wraps. An RTMP
//! Audio(8)/Video(9) message body is exactly one of these tag bodies (Adobe
//! RTMP 1.0 §7.1.4, §7.1.5), so the publisher and the demuxer share one
//! definition rather than each spelling the bit layout.
//!
//! See `private/specs-verified/mpeg/transmux/codec/flv.md` §E.4.1–§E.4.3.

use alloc::borrow::ToOwned;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use broadcast_core::error::BufferTooShort;
use broadcast_core::len::fit_mask;
use broadcast_core::wire::{Reader, Writer};
use broadcast_core::{Parse, Serialize};

use crate::RtmpError;
use crate::amf0::{Amf0Limits, Amf0Value, amf0_parse_values_with};
use crate::flv::PublishTrack;

type BodyResult<T> = core::result::Result<T, RtmpError>;

// ── Shared body constants (§E.4.2, §E.4.3) ──────────────────────────────

/// `FrameType` shift in the first `VideoTagHeader` byte (§E.4.3).
const FRAME_TYPE_SHIFT: u32 = 4;
/// `FrameType` mask in the first `VideoTagHeader` byte (§E.4.3).
const FRAME_TYPE_MASK: u8 = 0x0F;
/// `CodecID` mask in the first `VideoTagHeader` byte (§E.4.3).
const CODEC_ID_MASK: u8 = 0x0F;
/// `SoundFormat` mask in the first `AudioTagHeader` byte (§E.4.2).
const SOUND_FORMAT_MASK: u8 = 0x0F;
/// `SoundFormat` shift in the first `AudioTagHeader` byte (§E.4.2).
const SOUND_FORMAT_SHIFT: u32 = 4;
/// `SoundRate` shift in the first `AudioTagHeader` byte (§E.4.2).
const SOUND_RATE_SHIFT: u32 = 2;
/// `SoundSize` shift in the first `AudioTagHeader` byte (§E.4.2).
const SOUND_SIZE_SHIFT: u32 = 1;
/// `SoundType` mask in the first `AudioTagHeader` byte (§E.4.2).
const SOUND_TYPE_MASK: u8 = 0x01;
/// `SoundType` narrowing mask before the shift (the field is one bit).
const SOUND_FIELD_MASK: u8 = 0x03;

/// Byte width of the `VideoTagHeader` (§E.4.3): `FrameType` + `CodecID`.
pub const VIDEO_TAG_HEADER_LEN: usize = 1;
/// Byte offset of `AVCPacketType` in an `AVCVIDEOPACKET` (§E.4.3.2).
const AVC_PACKET_TYPE_AT: usize = 1;
/// Byte width of `AVCPacketType` (§E.4.3.2).
const AVC_PACKET_TYPE_LEN: usize = 1;
/// Byte offset of `CompositionTime` in an `AVCVIDEOPACKET` (§E.4.3.2).
const COMPOSITION_TIME_AT: usize = AVC_PACKET_TYPE_AT + AVC_PACKET_TYPE_LEN;
/// `CompositionTime` is a signed 24-bit field (§E.4.3.2).
const COMPOSITION_TIME_LEN: usize = 3;
/// Byte offset of the coded data after the `AVCVIDEOPACKET` header (§E.4.3.2).
pub const AVC_PACKET_DATA_OFFSET: usize = COMPOSITION_TIME_AT + COMPOSITION_TIME_LEN;
/// Smallest `CompositionTime` representable as the signed 24-bit `SI24`
/// field (§E.4.3.2).
pub const COMPOSITION_TIME_MIN: i32 = -(1 << 23);
/// Largest `CompositionTime` representable as the signed 24-bit `SI24`
/// field (§E.4.3.2).
pub const COMPOSITION_TIME_MAX: i32 = (1 << 23) - 1;

/// Byte width of the `AudioTagHeader` (§E.4.2): `SoundFormat` + `SoundRate`
/// + `SoundSize` + `SoundType`.
pub const AUDIO_TAG_HEADER_LEN: usize = 1;
/// Byte offset of `AACPacketType` in an `AACAUDIODATA` (§E.4.2.2).
const AAC_PACKET_TYPE_AT: usize = AUDIO_TAG_HEADER_LEN;
/// Byte offset of the raw AAC access unit (§E.4.2.2).
pub const AAC_PACKET_DATA_OFFSET: usize = AAC_PACKET_TYPE_AT + 1;

// ── VideoTagHeader (§E.4.3) ─────────────────────────────────────────────

/// FLV video `FrameType` (§E.4.3, Table E.4).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FrameType {
    /// 1: a keyframe (for AVC, a seekable frame).
    Keyframe,
    /// 2: an inter frame (for AVC, a non-seekable frame).
    Inter,
    /// 3: a disposable inter frame (H.263 only).
    DisposableInter,
    /// 4: a generated keyframe (reserved for server use only).
    GeneratedKeyframe,
    /// 5: video info / command frame.
    VideoInfo,
    /// 6, 7: reserved by the specification.
    Reserved(u8),
    /// 0, 8–15: outside the table, carried as written.
    Unknown(u8),
}

impl FrameType {
    /// The code this frame type carries in the `VideoTagHeader` nibble.
    pub fn to_code(self) -> u8 {
        match self {
            Self::Keyframe => 1,
            Self::Inter => 2,
            Self::DisposableInter => 3,
            Self::GeneratedKeyframe => 4,
            Self::VideoInfo => 5,
            Self::Reserved(code) | Self::Unknown(code) => code,
        }
    }

    /// The frame type a wire nibble names.
    pub fn from_code(code: u8) -> Self {
        match code {
            1 => Self::Keyframe,
            2 => Self::Inter,
            3 => Self::DisposableInter,
            4 => Self::GeneratedKeyframe,
            5 => Self::VideoInfo,
            6 | 7 => Self::Reserved(code),
            other => Self::Unknown(other),
        }
    }

    /// Whether this frame type is a keyframe (a seekable one) and so marks its
    /// sample as a sync point.
    #[must_use]
    pub fn is_keyframe(self) -> bool {
        matches!(self, Self::Keyframe | Self::GeneratedKeyframe)
    }

    /// The specification token for the tabled values (Table E.4).
    pub fn name(&self) -> &'static str {
        match self {
            Self::Keyframe => "keyframe",
            Self::Inter => "inter frame",
            Self::DisposableInter => "disposable inter frame",
            Self::GeneratedKeyframe => "generated keyframe",
            Self::VideoInfo => "video info/command frame",
            Self::Reserved(_) => "reserved",
            Self::Unknown(_) => "unknown",
        }
    }
}

broadcast_core::impl_spec_display!(FrameType, Reserved, Unknown);

/// FLV video `CodecID` (§E.4.3, Table E.5).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CodecId {
    /// 2: Sorenson H.263.
    SorensonH263,
    /// 3: Screen video.
    ScreenVideo,
    /// 4: On2 VP6.
    On2Vp6,
    /// 5: On2 VP6 with alpha channel.
    On2Vp6Alpha,
    /// 6: Screen video version 2.
    ScreenVideoV2,
    /// 7: AVC (H.264), carried as `AVCVIDEOPACKET` (§E.4.3.2).
    Avc,
    /// 12: HEVC (H.265), carried as `HEVCVIDEOPACKET`.
    Hevc,
    /// 0, 1, 8, 9 and 13–15: reserved by the specification.
    Reserved(u8),
    /// 10, 11: outside the table, carried as written.
    Unknown(u8),
}

impl CodecId {
    /// The code this codec id carries in the `VideoTagHeader` nibble.
    pub fn to_code(self) -> u8 {
        match self {
            Self::SorensonH263 => 2,
            Self::ScreenVideo => 3,
            Self::On2Vp6 => 4,
            Self::On2Vp6Alpha => 5,
            Self::ScreenVideoV2 => 6,
            Self::Avc => 7,
            Self::Hevc => 12,
            Self::Reserved(code) | Self::Unknown(code) => code,
        }
    }

    /// The codec id a wire nibble names.
    pub fn from_code(code: u8) -> Self {
        match code {
            2 => Self::SorensonH263,
            3 => Self::ScreenVideo,
            4 => Self::On2Vp6,
            5 => Self::On2Vp6Alpha,
            6 => Self::ScreenVideoV2,
            7 => Self::Avc,
            12 => Self::Hevc,
            10 | 11 => Self::Unknown(code),
            other => Self::Reserved(other),
        }
    }

    /// The specification token for the tabled values (Table E.5).
    pub fn name(&self) -> &'static str {
        match self {
            Self::SorensonH263 => "Sorenson H.263",
            Self::ScreenVideo => "Screen video",
            Self::On2Vp6 => "On2 VP6",
            Self::On2Vp6Alpha => "On2 VP6 with alpha channel",
            Self::ScreenVideoV2 => "Screen video version 2",
            Self::Avc => "AVC",
            Self::Hevc => "HEVC",
            Self::Reserved(_) => "reserved",
            Self::Unknown(_) => "unknown",
        }
    }
}

broadcast_core::impl_spec_display!(CodecId, Reserved, Unknown);

/// `AVCPacketType` of an AVC `AVCVIDEOPACKET` (§E.4.3.2).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AvcPacketType {
    /// 0: AVC sequence header — the `AVCDecoderConfigurationRecord` (`avcC`).
    SequenceHeader,
    /// 1: AVC NALU — one or more length-prefixed NAL units.
    Nalu,
    /// 2: AVC end of sequence (the body carries no data).
    EndOfSequence,
    /// 3 or above: outside the table, carried as written.
    Unknown(u8),
}

impl AvcPacketType {
    /// The code this packet type carries on the wire.
    pub fn to_code(self) -> u8 {
        match self {
            Self::SequenceHeader => 0,
            Self::Nalu => 1,
            Self::EndOfSequence => 2,
            Self::Unknown(code) => code,
        }
    }

    /// The packet type a wire byte names.
    pub fn from_code(code: u8) -> Self {
        match code {
            0 => Self::SequenceHeader,
            1 => Self::Nalu,
            2 => Self::EndOfSequence,
            other => Self::Unknown(other),
        }
    }

    /// The specification token for the tabled values (§E.4.3.2).
    pub fn name(&self) -> &'static str {
        match self {
            Self::SequenceHeader => "sequence header",
            Self::Nalu => "NALU",
            Self::EndOfSequence => "end of sequence",
            Self::Unknown(_) => "unknown",
        }
    }
}

broadcast_core::impl_spec_display!(AvcPacketType, Unknown);

/// The `VideoTagHeader` (§E.4.3) and, for the codecs that carry one, the
/// packet header of its `VIDEODATA` body.
///
/// `AVCVIDEOPACKET` (§E.4.3.2) is the only packet layout this crate decodes;
/// any other `CodecID` keeps all the bytes after the first byte as
/// [`data`](Self::data), because no packet header of that codec is modelled
/// here.
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VideoTagHeader<'a> {
    /// `FrameType` (§E.4.3).
    pub frame_type: FrameType,
    /// `CodecID` (§E.4.3).
    pub codec_id: CodecId,
    /// `AVCPacketType`: set only for [`CodecId::Avc`] (§E.4.3.2).
    pub avc_packet_type: Option<AvcPacketType>,
    /// `CompositionTime`, in milliseconds: set only for [`CodecId::Avc`]
    /// (§E.4.3.2). `PTS = DTS + CompositionTime`.
    pub composition_time: Option<i32>,
    /// The coded bytes after the packet header.
    pub data: &'a [u8],
}

impl<'a> VideoTagHeader<'a> {
    /// The header a publisher sent with no coded data.
    pub fn new(
        frame_type: FrameType,
        codec_id: CodecId,
        avc_packet_type: Option<AvcPacketType>,
        composition_time: Option<i32>,
    ) -> Self {
        Self {
            frame_type,
            codec_id,
            avc_packet_type,
            composition_time,
            data: &[],
        }
    }

    /// Whether a `CompositionTime` was stated for a codec that carries none
    /// (a `VideoTagHeader` from [`Self::parse`] never does).
    #[must_use]
    pub fn has_stray_composition_time(&self) -> bool {
        self.codec_id != CodecId::Avc && self.composition_time.is_some()
    }

    /// The packet type the wire carries: the stated `AVCPacketType` for an AVC
    /// body, and none for any other codec.
    fn avc_packet_type(&self) -> Option<AvcPacketType> {
        (self.codec_id == CodecId::Avc)
            .then_some(self.avc_packet_type)
            .flatten()
    }

    /// The `CompositionTime` the wire carries: the stated value for an AVC
    /// body, zero otherwise.
    fn composition_time(&self) -> i32 {
        if self.avc_packet_type().is_some() {
            self.composition_time.unwrap_or(0)
        } else {
            0
        }
    }

    /// The header's own bytes plus `data`, the whole `VIDEODATA` body.
    ///
    /// # Errors
    /// [`RtmpError::FieldOverflow`] when a `CompositionTime` does not fit the
    /// signed 24-bit field, and [`RtmpError::Malformed`] when one is stated for
    /// a codec that carries none.
    pub fn to_bytes(&self) -> BodyResult<Vec<u8>> {
        let len = self.serialized_len();
        let mut out = alloc::vec![0u8; len];
        let written = self.serialize_into(&mut out)?;
        debug_assert_eq!(written, len);
        Ok(out)
    }
}

impl<'a> Parse<'a> for VideoTagHeader<'a> {
    type Error = RtmpError;

    fn parse(bytes: &'a [u8]) -> BodyResult<Self> {
        let first = *bytes
            .first()
            .ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
                VIDEO_TAG_HEADER_LEN,
                bytes.len(),
                "FLV VideoTagHeader",
            )))?;
        let frame_type = FrameType::from_code(first >> FRAME_TYPE_SHIFT);
        let codec_id = CodecId::from_code(first & CODEC_ID_MASK);
        if codec_id != CodecId::Avc {
            return Ok(Self {
                frame_type,
                codec_id,
                avc_packet_type: None,
                composition_time: None,
                data: &bytes[VIDEO_TAG_HEADER_LEN..],
            });
        }
        if bytes.len() < AVC_PACKET_DATA_OFFSET {
            return Err(RtmpError::BufferTooShort(BufferTooShort::new(
                AVC_PACKET_DATA_OFFSET,
                bytes.len(),
                "FLV AVCVIDEOPACKET",
            )));
        }
        Ok(Self {
            frame_type,
            codec_id,
            avc_packet_type: Some(AvcPacketType::from_code(bytes[AVC_PACKET_TYPE_AT])),
            composition_time: Some(
                Reader::at(bytes, COMPOSITION_TIME_AT).i24("FLV AVCVIDEOPACKET")?,
            ),
            data: &bytes[AVC_PACKET_DATA_OFFSET..],
        })
    }
}

impl Serialize for VideoTagHeader<'_> {
    type Error = RtmpError;

    fn serialized_len(&self) -> usize {
        let mut len = VIDEO_TAG_HEADER_LEN;
        if self.codec_id == CodecId::Avc && self.avc_packet_type.is_some() {
            len += AVC_PACKET_DATA_OFFSET - VIDEO_TAG_HEADER_LEN;
        }
        len + self.data.len()
    }

    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
        if self.has_stray_composition_time() {
            return Err(RtmpError::Malformed {
                what: "FLV CompositionTime for a codec without AVCVIDEOPACKET",
            });
        }
        if self.codec_id == CodecId::Avc && self.avc_packet_type.is_none() {
            return Err(RtmpError::Malformed {
                what: "FLV AVCVIDEOPACKET without AVCPacketType",
            });
        }
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(RtmpError::OutputBufferTooSmall(
                broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "VideoTagHeader"),
            ));
        }
        let mut w = Writer::new(buf);
        let frame_type = fit_mask(self.frame_type.to_code(), FRAME_TYPE_MASK, "FrameType")?;
        let codec_id = fit_mask(self.codec_id.to_code(), CODEC_ID_MASK, "CodecID")?;
        w.u8(
            (frame_type << FRAME_TYPE_SHIFT) | codec_id,
            "FLV video tag frame type",
        )?;
        if let Some(packet_type) = self.avc_packet_type() {
            w.u8(packet_type.to_code(), "FLV video tag packet type")?;
            w.i24::<RtmpError>(self.composition_time(), "FLV CompositionTime")?;
        }
        w.bytes(self.data, "FLV video tag data")?;
        Ok(len)
    }
}

impl core::fmt::Debug for VideoTagHeader<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("VideoTagHeader")
            .field("frame_type", &self.frame_type)
            .field("codec_id", &self.codec_id)
            .field("avc_packet_type", &self.avc_packet_type)
            .field("composition_time", &self.composition_time)
            .field("data_len", &self.data.len())
            .finish()
    }
}

// ── AudioTagHeader (§E.4.2) ─────────────────────────────────────────────

/// `SoundFormat` of an `AudioTagHeader` (§E.4.2, Table E.6).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SoundFormat {
    /// 0: linear PCM, platform endian.
    LinearPcmPlatformEndian,
    /// 1: ADPCM.
    Adpcm,
    /// 2: MP3.
    Mp3,
    /// 3: linear PCM, little endian.
    LinearPcmLittleEndian,
    /// 4: Nellymoser 16 kHz mono.
    Nellymoser16KhzMono,
    /// 5: Nellymoser 8 kHz mono.
    Nellymoser8KhzMono,
    /// 6: Nellymoser.
    Nellymoser,
    /// 7: G.711 A-law logarithmic PCM.
    G711ALaw,
    /// 8: G.711 mu-law logarithmic PCM.
    G711MuLaw,
    /// 10: AAC, carried as `AACAUDIODATA` (§E.4.2.2).
    Aac,
    /// 11: Speex.
    Speex,
    /// 14: MP3 8 kHz.
    Mp3_8Khz,
    /// 15: device-specific sound.
    DeviceSpecific,
    /// 9: reserved by the specification.
    Reserved(u8),
    /// 12, 13: outside the table, carried as written.
    Unknown(u8),
}

impl SoundFormat {
    /// The code this sound format carries in the `AudioTagHeader` nibble.
    pub fn to_code(self) -> u8 {
        match self {
            Self::LinearPcmPlatformEndian => 0,
            Self::Adpcm => 1,
            Self::Mp3 => 2,
            Self::LinearPcmLittleEndian => 3,
            Self::Nellymoser16KhzMono => 4,
            Self::Nellymoser8KhzMono => 5,
            Self::Nellymoser => 6,
            Self::G711ALaw => 7,
            Self::G711MuLaw => 8,
            Self::Aac => 10,
            Self::Speex => 11,
            Self::Mp3_8Khz => 14,
            Self::DeviceSpecific => 15,
            Self::Reserved(code) | Self::Unknown(code) => code,
        }
    }

    /// The sound format a wire nibble names.
    pub fn from_code(code: u8) -> Self {
        match code {
            0 => Self::LinearPcmPlatformEndian,
            1 => Self::Adpcm,
            2 => Self::Mp3,
            3 => Self::LinearPcmLittleEndian,
            4 => Self::Nellymoser16KhzMono,
            5 => Self::Nellymoser8KhzMono,
            6 => Self::Nellymoser,
            7 => Self::G711ALaw,
            8 => Self::G711MuLaw,
            10 => Self::Aac,
            11 => Self::Speex,
            14 => Self::Mp3_8Khz,
            15 => Self::DeviceSpecific,
            12 | 13 => Self::Unknown(code),
            other => Self::Reserved(other),
        }
    }

    /// The specification token for the tabled values (Table E.6).
    pub fn name(&self) -> &'static str {
        match self {
            Self::LinearPcmPlatformEndian => "linear PCM, platform endian",
            Self::Adpcm => "ADPCM",
            Self::Mp3 => "MP3",
            Self::LinearPcmLittleEndian => "linear PCM, little endian",
            Self::Nellymoser16KhzMono => "Nellymoser 16 kHz mono",
            Self::Nellymoser8KhzMono => "Nellymoser 8 kHz mono",
            Self::Nellymoser => "Nellymoser",
            Self::G711ALaw => "G.711 A-law",
            Self::G711MuLaw => "G.711 mu-law",
            Self::Aac => "AAC",
            Self::Speex => "Speex",
            Self::Mp3_8Khz => "MP3 8 kHz",
            Self::DeviceSpecific => "device-specific sound",
            Self::Reserved(_) => "reserved",
            Self::Unknown(_) => "unknown",
        }
    }
}

broadcast_core::impl_spec_display!(SoundFormat, Reserved, Unknown);

/// `SoundRate` of an `AudioTagHeader` (§E.4.2, Table E.7).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SoundRate {
    /// 0: 5.5 kHz.
    Khz5_5_5,
    /// 1: 11 kHz.
    Khz11,
    /// 2: 22 kHz.
    Khz22,
    /// 3: 44 kHz (FLV carries no higher rate here; for AAC it is always 3 and
    /// the real rate lives in the `AudioSpecificConfig`).
    Khz44,
}

impl SoundRate {
    /// The code this rate carries on the wire.
    pub fn to_code(self) -> u8 {
        match self {
            Self::Khz5_5_5 => 0,
            Self::Khz11 => 1,
            Self::Khz22 => 2,
            Self::Khz44 => 3,
        }
    }

    /// The rate a wire code names.
    pub fn from_code(code: u8) -> Self {
        match code & SOUND_FIELD_MASK {
            0 => Self::Khz5_5_5,
            1 => Self::Khz11,
            2 => Self::Khz22,
            _ => Self::Khz44,
        }
    }

    /// The specification token for this rate (Table E.7).
    pub fn name(&self) -> &'static str {
        match self {
            Self::Khz5_5_5 => "5.5 kHz",
            Self::Khz11 => "11 kHz",
            Self::Khz22 => "22 kHz",
            Self::Khz44 => "44 kHz",
        }
    }
}

broadcast_core::impl_spec_display!(SoundRate);

/// `SoundSize` of an `AudioTagHeader` (§E.4.2, Table E.8).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SoundSize {
    /// 0: 8-bit samples.
    Bits8,
    /// 1: 16-bit samples.
    Bits16,
}

impl SoundSize {
    /// The code this size carries on the wire.
    pub fn to_code(self) -> u8 {
        match self {
            Self::Bits8 => 0,
            Self::Bits16 => 1,
        }
    }

    /// The size a wire bit names.
    pub fn from_code(code: u8) -> Self {
        if code & SOUND_TYPE_MASK == 0 {
            Self::Bits8
        } else {
            Self::Bits16
        }
    }

    /// The sample size in bits.
    pub fn bits(self) -> u8 {
        match self {
            Self::Bits8 => 8,
            Self::Bits16 => 16,
        }
    }

    /// The specification token for this size (Table E.8).
    pub fn name(&self) -> &'static str {
        match self {
            Self::Bits8 => "8-bit",
            Self::Bits16 => "16-bit",
        }
    }
}

broadcast_core::impl_spec_display!(SoundSize);

/// `SoundType` of an `AudioTagHeader` (§E.4.2, Table E.9).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SoundType {
    /// 0: mono.
    Mono,
    /// 1: stereo.
    Stereo,
}

impl SoundType {
    /// The code this sound type carries on the wire.
    pub fn to_code(self) -> u8 {
        match self {
            Self::Mono => 0,
            Self::Stereo => 1,
        }
    }

    /// The sound type a wire bit names.
    pub fn from_code(code: u8) -> Self {
        if code & SOUND_TYPE_MASK == 0 {
            Self::Mono
        } else {
            Self::Stereo
        }
    }

    /// The specification token for this sound type (Table E.9).
    pub fn name(&self) -> &'static str {
        match self {
            Self::Mono => "mono",
            Self::Stereo => "stereo",
        }
    }
}

broadcast_core::impl_spec_display!(SoundType);

/// `AACPacketType` of an AAC `AACAUDIODATA` (§E.4.2.2).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AacPacketType {
    /// 0: AAC sequence header — the `AudioSpecificConfig`.
    SequenceHeader,
    /// 1: AAC raw — one raw AAC access unit.
    Raw,
    /// 2 or above: outside the table, carried as written.
    Unknown(u8),
}

impl AacPacketType {
    /// The code this packet type carries on the wire.
    pub fn to_code(self) -> u8 {
        match self {
            Self::SequenceHeader => 0,
            Self::Raw => 1,
            Self::Unknown(code) => code,
        }
    }

    /// The packet type a wire byte names.
    pub fn from_code(code: u8) -> Self {
        match code {
            0 => Self::SequenceHeader,
            1 => Self::Raw,
            other => Self::Unknown(other),
        }
    }

    /// The specification token for the tabled values (§E.4.2.2).
    pub fn name(&self) -> &'static str {
        match self {
            Self::SequenceHeader => "sequence header",
            Self::Raw => "raw",
            Self::Unknown(_) => "unknown",
        }
    }
}

broadcast_core::impl_spec_display!(AacPacketType, Unknown);

/// The `AudioTagHeader` (§E.4.2) and, for AAC, the packet header of its
/// `AACAUDIODATA` body (§E.4.2.2).
///
/// `AACAUDIODATA` is the only audio packet layout this crate decodes; any
/// other `SoundFormat` keeps all the bytes after the first byte as
/// [`data`](Self::data), because no packet header of that codec is modelled
/// here.
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AudioTagHeader<'a> {
    /// `SoundFormat` (§E.4.2).
    pub sound_format: SoundFormat,
    /// `SoundRate` (§E.4.2).
    pub sound_rate: SoundRate,
    /// `SoundSize` (§E.4.2).
    pub sound_size: SoundSize,
    /// `SoundType` (§E.4.2).
    pub sound_type: SoundType,
    /// `AACPacketType`: set only for [`SoundFormat::Aac`] (§E.4.2.2).
    pub aac_packet_type: Option<AacPacketType>,
    /// The coded bytes after the packet header.
    pub data: &'a [u8],
}

impl<'a> AudioTagHeader<'a> {
    /// A header with no packet header and no coded data.
    pub fn new(
        sound_format: SoundFormat,
        sound_rate: SoundRate,
        sound_size: SoundSize,
        sound_type: SoundType,
        aac_packet_type: Option<AacPacketType>,
    ) -> Self {
        Self {
            sound_format,
            sound_rate,
            sound_size,
            sound_type,
            aac_packet_type,
            data: &[],
        }
    }

    /// The `SoundType` an audio `channel_count` states: one channel or fewer
    /// is mono, anything above is stereo (§E.5's `stereo` rule).
    #[must_use]
    pub fn sound_type_for_channels(channel_count: u16) -> SoundType {
        const MONO_CHANNELS: u16 = 1;
        if channel_count <= MONO_CHANNELS {
            SoundType::Mono
        } else {
            SoundType::Stereo
        }
    }

    /// The packet type the wire carries: the stated `AACPacketType` for AAC,
    /// and none for any other format.
    fn aac_packet_type(&self) -> Option<AacPacketType> {
        if self.sound_format == SoundFormat::Aac {
            self.aac_packet_type
        } else {
            None
        }
    }

    /// The header's own bytes plus `data`, the whole `AUDIODATA` body.
    ///
    /// # Errors
    /// [`RtmpError::Malformed`] when an `AACPacketType` is stated for a
    /// `SoundFormat` that carries none, or when an AAC body states none.
    pub fn to_bytes(&self) -> BodyResult<Vec<u8>> {
        if self.sound_format != SoundFormat::Aac && self.aac_packet_type.is_some() {
            return Err(RtmpError::Malformed {
                what: "FLV AACPacketType for a non-AAC SoundFormat",
            });
        }
        let len = self.serialized_len();
        let mut out = alloc::vec![0u8; len];
        let written = self.serialize_into(&mut out)?;
        debug_assert_eq!(written, len);
        Ok(out)
    }

    /// The `AudioTagHeader` first byte these sound fields make up (§E.4.2).
    ///
    /// # Errors
    /// [`RtmpError::FieldOverflow`] when a field's code does not fit its bits
    /// (a reserved or unknown code carries any byte).
    pub fn first_byte(&self) -> BodyResult<u8> {
        let format = fit_mask(
            self.sound_format.to_code(),
            SOUND_FORMAT_MASK,
            "SoundFormat",
        )?;
        let rate = fit_mask(self.sound_rate.to_code(), SOUND_FIELD_MASK, "SoundRate")?;
        let size = fit_mask(self.sound_size.to_code(), SOUND_TYPE_MASK, "SoundSize")?;
        let kind = fit_mask(self.sound_type.to_code(), SOUND_TYPE_MASK, "SoundType")?;
        Ok((format << SOUND_FORMAT_SHIFT)
            | (rate << SOUND_RATE_SHIFT)
            | (size << SOUND_SIZE_SHIFT)
            | kind)
    }
}

impl<'a> Parse<'a> for AudioTagHeader<'a> {
    type Error = RtmpError;

    fn parse(bytes: &'a [u8]) -> BodyResult<Self> {
        let first = *bytes
            .first()
            .ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
                AUDIO_TAG_HEADER_LEN,
                bytes.len(),
                "FLV AudioTagHeader",
            )))?;
        let sound_format = SoundFormat::from_code(first >> SOUND_FORMAT_SHIFT);
        let prefix = Self {
            sound_format,
            sound_rate: SoundRate::from_code(first >> SOUND_RATE_SHIFT),
            sound_size: SoundSize::from_code(first >> SOUND_SIZE_SHIFT),
            sound_type: SoundType::from_code(first),
            aac_packet_type: None,
            data: &[],
        };
        if sound_format != SoundFormat::Aac {
            return Ok(Self {
                data: &bytes[AUDIO_TAG_HEADER_LEN..],
                ..prefix
            });
        }
        let packet_type = *bytes
            .get(AAC_PACKET_TYPE_AT)
            .ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
                AAC_PACKET_DATA_OFFSET,
                bytes.len(),
                "FLV AACAUDIODATA",
            )))?;
        Ok(Self {
            aac_packet_type: Some(AacPacketType::from_code(packet_type)),
            data: &bytes[AAC_PACKET_DATA_OFFSET..],
            ..prefix
        })
    }
}

impl Serialize for AudioTagHeader<'_> {
    type Error = RtmpError;

    fn serialized_len(&self) -> usize {
        let mut len = AUDIO_TAG_HEADER_LEN;
        if self.aac_packet_type().is_some() {
            len += AAC_PACKET_DATA_OFFSET - AUDIO_TAG_HEADER_LEN;
        }
        len + self.data.len()
    }

    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
        if self.sound_format == SoundFormat::Aac && self.aac_packet_type.is_none() {
            return Err(RtmpError::Malformed {
                what: "FLV AACAUDIODATA without AACPacketType",
            });
        }
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(RtmpError::OutputBufferTooSmall(
                broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "AudioTagHeader"),
            ));
        }
        buf[0] = self.first_byte()?;
        let mut offset = AUDIO_TAG_HEADER_LEN;
        if let Some(packet_type) = self.aac_packet_type() {
            buf[AAC_PACKET_TYPE_AT] = packet_type.to_code();
            offset = AAC_PACKET_DATA_OFFSET;
        }
        buf[offset..len].copy_from_slice(self.data);
        Ok(len)
    }
}

impl core::fmt::Debug for AudioTagHeader<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("AudioTagHeader")
            .field("sound_format", &self.sound_format)
            .field("sound_rate", &self.sound_rate)
            .field("sound_size", &self.sound_size)
            .field("sound_type", &self.sound_type)
            .field("aac_packet_type", &self.aac_packet_type)
            .field("data_len", &self.data.len())
            .finish()
    }
}

// ── onMetaData (§E.4.1, AMF0 §2) ────────────────────────────────────────

/// FLV `videocodecid` for AVC (= [`CodecId::Avc`]'s code, §E.4.3).
pub const ON_METADATA_VIDEO_CODEC_ID_AVC: f64 = 7.0;
/// FLV `audiocodecid` for AAC (= [`SoundFormat::Aac`]'s code, §E.4.2).
pub const ON_METADATA_AUDIO_CODEC_ID_AAC: f64 = 10.0;

/// The handler name an `onMetaData` script body starts with (§E.4.1).
pub(crate) const META_HANDLER_NAME: &str = "onMetaData";
/// The handler name RTMP publishers put before `onMetaData` (§E.4.1; the FLV
/// file form starts with `onMetaData` directly). It addresses the server, not
/// the FLV script tag.
pub const SET_DATA_FRAME: &str = "@setDataFrame";
/// The `duration` property name.
const META_DURATION: &str = "duration";
/// The `width` property name.
const META_WIDTH: &str = "width";
/// The `height` property name.
const META_HEIGHT: &str = "height";
/// The `framerate` property name.
const META_FRAME_RATE: &str = "framerate";
/// The `videocodecid` property name.
const META_VIDEO_CODEC_ID: &str = "videocodecid";
/// The `audiosamplerate` property name.
const META_AUDIO_SAMPLE_RATE: &str = "audiosamplerate";
/// The `audiosamplesize` property name.
const META_AUDIO_SAMPLE_SIZE: &str = "audiosamplesize";
/// The `stereo` property name.
const META_STEREO: &str = "stereo";
/// The `audiocodecid` property name.
const META_AUDIO_CODEC_ID: &str = "audiocodecid";
/// The `filesize` property name.
const META_FILE_SIZE: &str = "filesize";
/// The `encoder` property name.
const META_ENCODER: &str = "encoder";

/// The informational properties an `onMetaData` script tag states, typed.
///
/// Adobe FLV v10.1 §E.4.1 defines the script-data tag and the `onMetaData`
/// handler but not the property list
/// (`private/specs-verified/mpeg/transmux/codec/flv.md` §E.4.1). The property
/// names are the de-facto set real FLV writers emit (`duration`, `width`, `height`, `framerate`,
/// `videocodecid`, `audiosamplerate`, `audiosamplesize`, `stereo`,
/// `audiocodecid`, `filesize`, `encoder`); a property the writer stated that
/// this crate does not name stays in [`properties`](Self::properties) as the
/// AMF0 value the body carried.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OnMetadata {
    body: Vec<u8>,
    properties: Vec<(String, Amf0Value)>,
    duration: Option<f64>,
    width: Option<u16>,
    height: Option<u16>,
    frame_rate: Option<f64>,
    video_codec_id: Option<f64>,
    audio_sample_rate: Option<u32>,
    audio_sample_size: Option<u16>,
    stereo: Option<bool>,
    audio_codec_id: Option<f64>,
    file_size: Option<u64>,
    encoder: Option<String>,
}

impl OnMetadata {
    /// The `onMetaData` body — the AMF0 `onMetaData` name followed by one ECMA
    /// array of the informational properties players read, in the order they
    /// are written (§E.4.1, AMF0 §2) — that every FLV/RTMP writer emits, so a
    /// file muxed by an FLV muxer and a stream published over RTMP describe
    /// the same tracks with the same bytes.
    ///
    /// `duration` is the only property a caller decides: a file knows its own
    /// length, a live publisher does not and passes `None`, which omits the
    /// key rather than claiming a length. At least one of `tracks` must be AVC
    /// video or AAC audio for a body to be stated at all; every other track
    /// contributes no property.
    ///
    /// # Errors
    /// [`RtmpError::Malformed`] when `tracks` holds neither an AVC video nor
    /// an AAC audio track, and [`RtmpError::FieldOverflow`] when a key exceeds
    /// its AMF0 length prefix.
    pub fn new(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
        Self::with_session(tracks, duration, None, None)
    }

    /// [`Self::new`] plus the two whole-stream properties a demuxer carries
    /// across from a source it re-reads: the source's script tag
    /// ([`Self::raw_body`], read under the caller's AMF0 limits) and the source's file size in
    /// bytes.
    ///
    /// A `source` whose handler is not `onMetaData` (an
    /// [`SET_DATA_FRAME`]-wrapped body is unwrapped first) is
    /// [`RtmpError::Malformed`].
    ///
    /// # Errors
    /// As [`Self::new`], plus [`RtmpError::Malformed`] for an unusable source
    /// body.
    pub fn with_session(
        tracks: &[PublishTrack],
        duration: Option<f64>,
        source: Option<(&[u8], Amf0Limits)>,
        file_size: Option<u64>,
    ) -> BodyResult<Self> {
        let metadata = Self::from_tracks(tracks, duration)?;
        if let Some((source, limits)) = source {
            let mut reference = Self::parse_body(source, true, limits)?;
            if file_size.is_some() {
                reference.file_size = file_size;
            }
            return Ok(reference);
        }
        let Some(file_size) = file_size else {
            return Ok(metadata);
        };
        let mut properties = metadata.properties;
        properties.push((
            META_FILE_SIZE.to_string(),
            Amf0Value::Number(file_size as f64),
        ));
        let stated = Self::from_properties(&[], properties);
        let body = stated.script_body()?;
        Ok(Self::from_properties(&body, stated.properties))
    }

    /// The properties `tracks` and `duration` state, read back into the typed
    /// view.
    fn from_tracks(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
        let video = tracks.iter().find_map(|track| match track {
            PublishTrack::Video { width, height, .. } => Some((*width, *height)),
            PublishTrack::Audio { .. } => None,
        });
        let audio = tracks.iter().find_map(|track| match track {
            PublishTrack::Audio {
                sample_rate,
                channel_count,
                ..
            } => Some((*sample_rate, *channel_count)),
            PublishTrack::Video { .. } => None,
        });
        if video.is_none() && audio.is_none() {
            return Err(RtmpError::Malformed {
                what: "onMetaData without an AVC video or AAC audio track",
            });
        }
        let mut properties: Vec<(String, Amf0Value)> = Vec::new();
        if let Some(duration) = duration {
            properties.push((META_DURATION.to_string(), Amf0Value::Number(duration)));
        }
        if let Some((width, height)) = video {
            properties.push((META_WIDTH.to_string(), Amf0Value::Number(f64::from(width))));
            properties.push((
                META_HEIGHT.to_string(),
                Amf0Value::Number(f64::from(height)),
            ));
            properties.push((
                META_VIDEO_CODEC_ID.to_string(),
                Amf0Value::Number(ON_METADATA_VIDEO_CODEC_ID_AVC),
            ));
        }
        if let Some((sample_rate, channel_count)) = audio {
            properties.push((
                META_AUDIO_CODEC_ID.to_string(),
                Amf0Value::Number(ON_METADATA_AUDIO_CODEC_ID_AAC),
            ));
            properties.push((
                META_AUDIO_SAMPLE_RATE.to_string(),
                Amf0Value::Number(f64::from(sample_rate)),
            ));
            properties.push((
                META_STEREO.to_string(),
                Amf0Value::Boolean(
                    AudioTagHeader::sound_type_for_channels(channel_count) == SoundType::Stereo,
                ),
            ));
        }
        Ok(Self::from_properties(&[], properties))
    }

    /// This value as its wire bytes: the `onMetaData` handler name followed by
    /// the properties as one ECMA array.
    ///
    /// # Errors
    /// [`RtmpError::FieldOverflow`] when a key exceeds its AMF0 length prefix.
    pub fn serialize_into_vec(&self) -> BodyResult<Vec<u8>> {
        let mut out = alloc::vec![0u8; self.serialized_len()];
        let written = self.serialize_into(&mut out)?;
        out.truncate(written);
        Ok(out)
    }

    /// The whole-stream duration in seconds, when the writer stated it.
    #[must_use]
    pub const fn duration(&self) -> Option<f64> {
        self.duration
    }

    /// The coded picture width in pixels.
    #[must_use]
    pub const fn width(&self) -> Option<u16> {
        self.width
    }

    /// The coded picture height in pixels.
    #[must_use]
    pub const fn height(&self) -> Option<u16> {
        self.height
    }

    /// The frame rate in frames per second.
    #[must_use]
    pub const fn frame_rate(&self) -> Option<f64> {
        self.frame_rate
    }

    /// The `videocodecid` the writer stated.
    #[must_use]
    pub const fn video_codec_id(&self) -> Option<f64> {
        self.video_codec_id
    }

    /// The audio sample rate in Hz.
    #[must_use]
    pub const fn audio_sample_rate(&self) -> Option<u32> {
        self.audio_sample_rate
    }

    /// The audio sample size in bits.
    #[must_use]
    pub const fn audio_sample_size(&self) -> Option<u16> {
        self.audio_sample_size
    }

    /// Whether the writer stated a two-channel stream.
    #[must_use]
    pub const fn stereo(&self) -> Option<bool> {
        self.stereo
    }

    /// The `audiocodecid` the writer stated.
    #[must_use]
    pub const fn audio_codec_id(&self) -> Option<f64> {
        self.audio_codec_id
    }

    /// The file size the writer stated, in bytes.
    #[must_use]
    pub const fn file_size(&self) -> Option<u64> {
        self.file_size
    }

    /// The encoding application's name.
    #[must_use]
    pub fn encoder(&self) -> Option<&str> {
        self.encoder.as_deref()
    }

    /// The script-data body this metadata came from — or the properties
    /// rendered as a body when it came from tracks
    /// ([`Self::with_session`]'s `source`) — so a remux can write the same
    /// bytes back rather than re-encoding the properties.
    #[must_use]
    pub fn raw_body(&self) -> &[u8] {
        &self.body
    }

    /// Every property the script tag carried, in the order it carried them.
    #[must_use]
    pub fn properties(&self) -> &[(String, Amf0Value)] {
        &self.properties
    }

    /// One property by name, as the body carried it.
    #[must_use]
    pub fn property(&self, name: &str) -> Option<&Amf0Value> {
        self.properties
            .iter()
            .find(|(key, _)| key == name)
            .map(|(_, value)| value)
    }

    /// Read an `onMetaData` script-data body (§E.4.1, AMF0 §2).
    ///
    /// The body is the handler name followed by one property object or ECMA
    /// array; an [`SET_DATA_FRAME`] wrapper is accepted. Anything else, or a
    /// body that does not parse as AMF0, is not interpretation: `None`.
    #[must_use]
    pub fn parse(body: &[u8], limits: Amf0Limits) -> Option<Self> {
        Self::parse_body(body, false, limits).ok()
    }

    /// [`Self::parse`], reporting why a body was not interpretation.
    ///
    /// # Errors
    /// [`RtmpError::Malformed`] when the handler is not `onMetaData` or no
    /// property object follows it, and the AMF0 error when the body does not
    /// decode.
    pub fn parse_body(body: &[u8], retain_raw: bool, limits: Amf0Limits) -> BodyResult<Self> {
        Self::parse_body_with_diagnostics(body, retain_raw, limits).map(|(metadata, _)| metadata)
    }

    /// [`Self::parse_body`], also returning every AMF0 defect the body carried that did not stop
    /// it being usable, as reports the caller can publish.
    ///
    /// # Errors
    /// Exactly as [`Self::parse_body`].
    pub fn parse_body_with_diagnostics(
        body: &[u8],
        retain_raw: bool,
        limits: Amf0Limits,
    ) -> BodyResult<(Self, Vec<broadcast_core::damage::Damage>)> {
        let (values, diagnostics) = amf0_parse_values_with(body, limits)?;
        let mut values = values.into_iter();
        let handler = handler_name(values.next())?;
        let handler = if handler == SET_DATA_FRAME {
            handler_name(values.next())?
        } else {
            handler
        };
        if handler != META_HANDLER_NAME {
            return Err(RtmpError::Malformed {
                what: "FLV onMetaData handler name",
            });
        }
        let properties = match values.next() {
            Some(Amf0Value::EcmaArray(properties) | Amf0Value::Object(properties)) => properties,
            _ => {
                return Err(RtmpError::Malformed {
                    what: "FLV onMetaData property object",
                });
            }
        };
        let retained = if retain_raw { body } else { &[] };
        Ok((Self::from_properties(retained, properties), diagnostics))
    }

    /// Read the typed view out of a property list.
    fn from_properties(body: &[u8], properties: Vec<(String, Amf0Value)>) -> Self {
        let number = |name: &str| match find_property(&properties, name) {
            Some(Amf0Value::Number(value)) => Some(*value),
            _ => None,
        };
        let whole16 = |name: &str| {
            number(name)
                .and_then(whole_number)
                .and_then(|n| u16::try_from(n).ok())
        };
        let whole32 = |name: &str| {
            number(name)
                .and_then(whole_number)
                .and_then(|n| u32::try_from(n).ok())
        };
        let whole64 = |name: &str| number(name).and_then(whole_number);
        let encoder = match find_property(&properties, META_ENCODER) {
            Some(Amf0Value::String(encoder) | Amf0Value::LongString(encoder)) => {
                Some(encoder.clone())
            }
            _ => None,
        };
        Self {
            body: body.to_vec(),
            duration: number(META_DURATION),
            width: whole16(META_WIDTH),
            height: whole16(META_HEIGHT),
            frame_rate: number(META_FRAME_RATE),
            video_codec_id: number(META_VIDEO_CODEC_ID),
            audio_sample_rate: whole32(META_AUDIO_SAMPLE_RATE),
            audio_sample_size: whole16(META_AUDIO_SAMPLE_SIZE),
            stereo: match find_property(&properties, META_STEREO) {
                Some(Amf0Value::Boolean(stereo)) => Some(*stereo),
                _ => None,
            },
            audio_codec_id: number(META_AUDIO_CODEC_ID),
            file_size: whole64(META_FILE_SIZE),
            encoder,
            properties,
        }
    }
}

impl OnMetadata {
    /// This metadata as the FLV script tag body (§E.4.1): the `onMetaData`
    /// handler name followed by the properties as one ECMA array.
    ///
    /// # Errors
    /// [`RtmpError::FieldOverflow`] when a key exceeds its AMF0 length prefix.
    pub fn script_body(&self) -> BodyResult<Vec<u8>> {
        let name = Amf0Value::String(META_HANDLER_NAME.to_string());
        let array = Amf0Value::EcmaArray(self.properties.clone());
        let len = name.serialized_len() + array.serialized_len();
        let mut body = alloc::vec![0u8; len];
        let written = name.serialize_into(&mut body)?;
        let rest = written + array.serialize_into(&mut body[written..])?;
        debug_assert_eq!(rest, len);
        Ok(body)
    }
}

impl OnMetadata {
    /// This metadata as the RTMP Data-AMF0 message payload a publisher sends
    /// (Adobe RTMP 1.0 §7.1.2): `@setDataFrame`, then the file form
    /// (`onMetaData` and the properties as one ECMA array), the form a real
    /// publisher sends (`fixtures/rtmp/obs-publish.bin`) and the inverse of
    /// [`strip_set_data_frame`].
    ///
    /// [`script_body`](Self::script_body) is the other wire form of the same
    /// properties: the FLV file's script tag.
    ///
    /// # Errors
    /// [`RtmpError::FieldOverflow`] when a key exceeds its AMF0 length prefix.
    pub fn publish_body(&self) -> BodyResult<Vec<u8>> {
        set_data_frame_body(&self.properties)
    }
}

/// The `@setDataFrame`/`onMetaData` data message payload for `metadata`, held
/// as one AMF0 ECMA array after the handler name (Adobe RTMP 1.0 §7.1.2).
///
/// # Errors
/// [`RtmpError::Amf0StringTooLong`] / [`RtmpError::FieldOverflow`] when a
/// string or key does not fit its AMF0 length prefix.
pub(crate) fn set_data_frame_body(metadata: &[(String, Amf0Value)]) -> BodyResult<Vec<u8>> {
    let mut payload = Amf0Value::String(SET_DATA_FRAME.to_string()).try_to_bytes()?;
    payload.extend(Amf0Value::String(META_HANDLER_NAME.to_string()).try_to_bytes()?);
    payload.extend(Amf0Value::EcmaArray(metadata.to_vec()).try_to_bytes()?);
    Ok(payload)
}

impl Serialize for OnMetadata {
    type Error = RtmpError;

    fn try_to_bytes(&self) -> core::result::Result<Vec<u8>, Self::Error> {
        let mut out = alloc::vec![0u8; self.serialized_len()];
        let written = self.serialize_into(&mut out)?;
        out.truncate(written);
        Ok(out)
    }

    /// The `onMetaData` handler name followed by the properties as one ECMA
    /// array: the file form of the script-data tag body.
    fn serialized_len(&self) -> usize {
        if !self.body.is_empty() {
            return strip_set_data_frame(&self.body).len();
        }
        let name = Amf0Value::String(META_HANDLER_NAME.to_string());
        name.serialized_len() + Amf0Value::EcmaArray(self.properties.clone()).serialized_len()
    }

    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
        let len = self.serialized_len();
        if buf.len() < len {
            return Err(RtmpError::OutputBufferTooSmall(
                broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "OnMetadata"),
            ));
        }
        if !self.body.is_empty() {
            buf[..len].copy_from_slice(strip_set_data_frame(&self.body));
            return Ok(len);
        }
        let name = Amf0Value::String(META_HANDLER_NAME.to_string());
        let written = name.serialize_into(buf)?;
        let array = Amf0Value::EcmaArray(self.properties.clone());
        let rest = written + array.serialize_into(&mut buf[written..])?;
        debug_assert_eq!(rest, len);
        Ok(rest)
    }
}

/// The handler name an AMF0 value states.
fn handler_name(value: Option<Amf0Value>) -> BodyResult<String> {
    match value {
        Some(Amf0Value::String(handler)) => Ok(handler),
        _ => Err(RtmpError::Malformed {
            what: "FLV onMetaData handler name",
        }),
    }
}

/// A property's value by name.
fn find_property<'a>(properties: &'a [(String, Amf0Value)], name: &str) -> Option<&'a Amf0Value> {
    properties
        .iter()
        .find(|(key, _)| key == name)
        .map(|(_, value)| value)
}

/// A finite, non-negative number with no fractional part, as an integer.
///
/// The `f64` methods (`trunc`, `is_finite`) are `std`-only, so the core build
/// (no `std`, no `target`/`tokio`) decides the same way through the
/// `PartialOrd`/`PartialEq` comparisons the values themselves support.
fn whole_number(value: f64) -> Option<u64> {
    const LOWEST: f64 = 0.0;
    // A NaN fails the comparison, so it is ruled out with every other value
    // outside the range.
    if value < LOWEST || value > u64::MAX as f64 {
        return None;
    }
    (value as u64 as f64 == value).then_some(value as u64)
}

/// `body` without a leading AMF0 `@setDataFrame` string, so the FLV script tag
/// begins with `onMetaData` as §E.4.1 defines it.
#[must_use]
pub fn strip_set_data_frame(body: &[u8]) -> &[u8] {
    let Ok(name) = Amf0Value::String(SET_DATA_FRAME.to_owned()).try_to_bytes() else {
        return body;
    };
    body.strip_prefix(name.as_slice()).unwrap_or(body)
}

#[cfg(test)]
#[path = "tag_body_tests.rs"]
mod tests;