rtmp-runtime 0.13.0

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
//! FLV (Flash Video) tag framing — Adobe Flash Video File Format Specification
//! **v10.1, Annex E**: the file header of §E.2 and the tag of §E.4.1.
//!
//! This is the one implementation of the FLV tag layer in the workspace (#2342): the
//! `rtmp-runtime` session engine hands its callers FLV bytes (RTMP Audio(8)/Video(9)/
//! Data-AMF0(18) message bodies are FLV tag bodies, Adobe RTMP 1.0 §7.1.4, §7.1.5,
//! §7.1.2), and `transmux` builds its FLV streams from the same values instead of a
//! second encoder. What a tag *contains* (codec headers, sequence headers, composition
//! time) is the caller's business; this module only frames it.
//!
//! # Layout (Annex E)
//!
//! - **Header** (§E.2, 9 bytes) + `PreviousTagSize0` (4 bytes, = 0): `"FLV"`
//!   signature, `Version`, `TypeFlags` (bit 0 audio, bit 2 video), and the
//!   `DataOffset`.
//! - **Tag** (§E.4.1): an 11-byte header (`TagType` UI8, `DataSize` UI24,
//!   `Timestamp` UI24 + `TimestampExtended` UI8, `StreamID` UI24 = 0), the body,
//!   and the UI32 `PreviousTagSize` (11 + `DataSize`).
//!
//! Spec: `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` sections 6.6 and 9.
//!
//! What a tag *body* is — `VideoTagHeader`+`AVCVIDEOPACKET` (§E.4.3),
//! `AudioTagHeader`+`AACAUDIODATA` (§E.4.2) and the `onMetaData` script body
//! (§E.4.1) — is defined beside this framing and re-exported here.

mod publish;
mod tag_body;

#[cfg(test)]
mod publish_tests;

#[cfg(feature = "target")]
pub use publish::PublishTarget;
pub use publish::{PublishMessage, PublishTrack, publish_open};
pub(crate) use tag_body::set_data_frame_body;
pub use tag_body::{
    AAC_PACKET_DATA_OFFSET, AUDIO_TAG_HEADER_LEN, AVC_PACKET_DATA_OFFSET, AacPacketType,
    AudioTagHeader, AvcPacketType, COMPOSITION_TIME_MAX, COMPOSITION_TIME_MIN, CodecId, FrameType,
    ON_METADATA_AUDIO_CODEC_ID_AAC, ON_METADATA_VIDEO_CODEC_ID_AVC, OnMetadata, SET_DATA_FRAME,
    SoundFormat, SoundRate, SoundSize, SoundType, VIDEO_TAG_HEADER_LEN, VideoTagHeader,
    strip_set_data_frame,
};

use broadcast_core::error::OutputBufferTooSmall;
use broadcast_core::len::{fit_u24, fit_u32, need_in, need_out};
use broadcast_core::wire::{Reader, Writer};
use broadcast_core::{Parse, Serialize};

use crate::RtmpError;
use crate::chunk::Message;
use crate::message::MessageTypeId;
use alloc::vec::Vec;

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

/// The `OutputBufferTooSmall` a serializer returns when a buffer that passed
/// its pre-check still cannot be sliced to the needed length.
fn make_output_too_small(need: usize, have: usize) -> OutputBufferTooSmall {
    OutputBufferTooSmall::new(need, have, "FLV")
}

// ── Aggregate message consts (§7.1.6 / Adobe FLV v10.1 Annex E.5) ───────

/// Byte width of an Aggregate (22) sub-message header (§7.1.6, FLV
/// Annex E.5): `Type`(1) + `DataSize`(3) + `Timestamp`(3) +
/// `TimestampExtended`(1) + `StreamID`(3).
pub(crate) const AGG_SUB_MESSAGE_HEADER_LEN: usize = 11;
/// Byte width of the `Back Pointer` field following each Aggregate
/// sub-message (§7.1.6): "size of the previous message including its
/// header" — the same value the enclosing FLV `PreviousTagSize` convention
/// describes (FLV Annex E.4.1's tag-header field + 24-bit `DataSize`).
pub(crate) const AGG_BACK_POINTER_LEN: usize = 4;
/// `TimestampExtended`'s shift into the top byte of a 32-bit timestamp:
/// same layout the top-level `flv_tag` writes (FLV Annex E.4.1) — the
/// 24-bit `Timestamp` field holds the low 24 bits, `TimestampExtended` the
/// top 8.
pub(crate) const AGG_TIMESTAMP_EXTENDED_SHIFT: u32 = 24;

/// Unpack an Aggregate Message (22, §7.1.6), calling `deliver(tag_type, timestamp, payload)` for
/// each contained Audio, Video or Data-AMF0 sub-message as an ordinary one would be delivered
/// (§7.1.6 allows no other type); a sub-message of any other type is reported on `damage` as
/// uninterpreted and not delivered.
///
/// Sub-message layout (§7.1.6, identical to the FLV tag layout of Adobe FLV v10.1 Annex
/// E.4.1/E.5): `Type`(1) + `DataSize`(3) + `Timestamp`(3) + `TimestampExtended`(1) + `StreamID`(3,
/// always 0) + `Data` + `Back Pointer`(4). Per §7.1.6 the aggregate's own message stream id
/// overrides every sub-message's, and sub-message timestamps are renormalized by `offset =
/// aggregate ts - first sub-message ts` added to each sub-message timestamp.
///
/// A sub-message header or `DataSize`-claimed data run reaching past the end of the aggregate
/// body, or a `Back Pointer` that disagrees with the sub-message's actual size, ends the
/// aggregate: the sub-messages before the malformed one were already delivered, and one is
/// pushed onto `damage` for the rest. The connection itself is unaffected — the aggregate's
/// own framing arrived intact, so the next message is still locatable.
///
/// # Errors
/// Whatever `deliver` returns.
pub(crate) fn unpack_aggregate(
    msg: &Message,
    damage: &mut Vec<broadcast_core::damage::Damage>,
    mut deliver: impl FnMut(MessageTypeId, u32, &[u8]) -> FlvResult<()>,
) -> FlvResult<()> {
    let body = &msg.payload;
    let mut first_ts: Option<u32> = None;
    let mut offset = 0usize;
    while offset < body.len() {
        if body.len() - offset < AGG_SUB_MESSAGE_HEADER_LEN {
            damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
            return Ok(());
        }
        let header = &body[offset..offset + AGG_SUB_MESSAGE_HEADER_LEN];
        let tag_type = MessageTypeId::from_u8(header[0]);
        let data_size =
            Reader::at(header, TAG_DATA_SIZE_AT).u24("FLV aggregate sub-message")? as usize;
        let ts_low24 = Reader::at(header, TAG_TIMESTAMP_AT).u24("FLV aggregate sub-message")?;
        // Same layout `flv_tag` writes (Annex E.4.1): the 24-bit
        // `Timestamp` field holds bits 0..=23, `TimestampExtended`
        // holds the top 8.
        let raw_ts = ts_low24
            | (u32::from(header[TAG_TIMESTAMP_EXTENDED_AT]) << AGG_TIMESTAMP_EXTENDED_SHIFT);
        // header[8..11] is the sub-message `StreamID` (always 0):
        // §7.1.6 says the aggregate's own message stream id overrides
        // every sub-message's stream id anyway, so it is ignored.
        let data_start = offset + AGG_SUB_MESSAGE_HEADER_LEN;
        let Some(data_end) = data_size.checked_add(data_start) else {
            damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
            return Ok(());
        };
        let back_end = match data_end.checked_add(AGG_BACK_POINTER_LEN) {
            Some(end) if end <= body.len() => end,
            _ => {
                damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
                return Ok(());
            }
        };
        let back_pointer = Reader::at(body, back_end - AGG_BACK_POINTER_LEN).u32("Back Pointer")?;
        let expected_back_pointer = match broadcast_core::len::fit_u32(
            AGG_SUB_MESSAGE_HEADER_LEN + data_size,
            "Back Pointer",
        ) {
            Ok(v) => v,
            Err(_) => {
                damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
                return Ok(());
            }
        };
        if back_pointer != expected_back_pointer {
            damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
            return Ok(());
        }

        let ts_offset = *first_ts.get_or_insert(raw_ts);
        // §7.1.6: offset = (aggregate ts − first sub-message ts), added
        // to each sub-message ts.
        let adjusted = raw_ts.wrapping_add(msg.timestamp.millis().wrapping_sub(ts_offset));
        if matches!(
            tag_type,
            MessageTypeId::Audio | MessageTypeId::Video | MessageTypeId::DataAmf0
        ) {
            deliver(tag_type, adjusted, &body[data_start..data_end])?;
        } else {
            damage.push(crate::damage::uninterpreted(
                "RTMP aggregate sub-message type",
            ));
        }
        offset = back_end;
    }
    Ok(())
}

// ── File header (§E.2) ──────────────────────────────────────────────────

/// FLV file header `Signature` field (§E.2): `"FLV"`.
pub const FLV_SIGNATURE: [u8; 3] = *b"FLV";
/// FLV file header `Version` field this crate writes (§E.2).
pub const FLV_VERSION: u8 = 1;
/// `TypeFlags` bit 0 — audio tags present (§E.2).
pub const FLV_FLAG_AUDIO: u8 = 0x04;
/// `TypeFlags` bit 2 — video tags present (§E.2).
pub const FLV_FLAG_VIDEO: u8 = 0x01;
/// Byte width of the file header's fixed part (§E.2): `Signature`(3) +
/// `Version`(1) + `TypeFlags`(1) + `DataOffset`(4).
pub const FLV_HEADER_LEN: usize = 9;
/// Offset of the file header's `TypeFlags` byte (§E.2).
const FLV_FLAGS_OFFSET: usize = 4;
/// Offset of the file header's 4-byte `DataOffset` field (§E.2).
const FLV_DATA_OFFSET_FIELD: usize = 5;
/// Byte width of the `PreviousTagSize0` field that follows the file header
/// (§E.2) and of the `PreviousTagSize` field after every tag (§E.4.1).
pub const FLV_PREV_TAG_SIZE_LEN: usize = 4;
/// Byte width of one tag's fixed header (§E.4.1): `TagType`(1) +
/// `DataSize`(3) + `Timestamp`(3) + `TimestampExtended`(1) + `StreamID`(3).
pub const FLV_TAG_HEADER_LEN: usize = 11;
/// The `DataOffset` this crate writes: the header is exactly
/// [`FLV_HEADER_LEN`] bytes (§E.2).
pub const FLV_DATA_OFFSET: u32 = 9;
/// Bit position of `TimestampExtended`, which carries the top 8 bits of the
/// tag's 32-bit millisecond `Timestamp` (§E.4.1).
pub const FLV_TIMESTAMP_EXTENDED_SHIFT: u32 = 24;
/// `StreamID` value of every tag this crate writes (§E.4.1).
pub const FLV_STREAM_ID: u32 = 0;

/// The FLV file header (§E.2), including the `PreviousTagSize0` that always
/// follows it.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FlvHeader<'a> {
    /// `TypeFlags` bit 0 (§E.2): the file carries audio tags.
    pub has_audio: bool,
    /// `TypeFlags` bit 2 (§E.2): the file carries video tags.
    pub has_video: bool,
    /// The `DataOffset - 9` extra header bytes between the fixed 9-byte
    /// header and the `PreviousTagSize0` that the parser skipped (§E.2).
    /// Empty on every header this crate writes. The `DataOffset` field itself
    /// is derived from this length ([`FlvHeader::data_offset`]), never stored
    /// beside it, so a serialized header always declares exactly the bytes it
    /// carries.
    pub extra: &'a [u8],
}

impl<'a> FlvHeader<'a> {
    /// A header declaring the given track kinds, with the standard
    /// `DataOffset`.
    pub fn new(has_audio: bool, has_video: bool) -> Self {
        Self {
            has_audio,
            has_video,
            extra: &[],
        }
    }

    /// The `TypeFlags` byte (§E.2) this header puts on the wire.
    pub fn type_flags(&self) -> u8 {
        let mut flags = 0u8;
        if self.has_audio {
            flags |= FLV_FLAG_AUDIO;
        }
        if self.has_video {
            flags |= FLV_FLAG_VIDEO;
        }
        flags
    }

    /// The `DataOffset` (§E.2) this header declares: [`FLV_HEADER_LEN`] plus
    /// the length of [`FlvHeader::extra`].
    pub fn data_offset(&self) -> usize {
        FLV_HEADER_LEN.saturating_add(self.extra.len())
    }

    /// Offset of the first tag's header: past the `DataOffset` the header
    /// declares and its `PreviousTagSize0` (§E.2).
    pub fn first_tag_offset(&self) -> usize {
        self.data_offset().saturating_add(FLV_PREV_TAG_SIZE_LEN)
    }
}

impl FlvHeader<'_> {
    /// The `DataOffset` the fixed 9-byte header declares (FLV §E.2), after
    /// checking the signature, without requiring the bytes it points past.
    /// A streaming reader uses it to bound how much it buffers before the
    /// whole header has arrived.
    pub fn declared_data_offset(bytes: &[u8]) -> FlvResult<u32> {
        need_in(bytes, FLV_HEADER_LEN, "FLV header")?;
        if bytes.get(..FLV_SIGNATURE.len()) != Some(FLV_SIGNATURE.as_slice()) {
            return Err(RtmpError::Malformed {
                what: "FLV header signature",
            });
        }
        let field = bytes
            .get(FLV_DATA_OFFSET_FIELD..FLV_HEADER_LEN)
            .and_then(|b| <[u8; U32_LEN]>::try_from(b).ok())
            .ok_or(RtmpError::Malformed {
                what: "FLV header DataOffset",
            })?;
        Ok(u32::from_be_bytes(field))
    }
}

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

    fn parse(bytes: &'a [u8]) -> FlvResult<Self> {
        let declared = FlvHeader::declared_data_offset(bytes)?;
        let flags = bytes[FLV_FLAGS_OFFSET];
        let data_offset = usize::try_from(declared).map_err(|_| RtmpError::Malformed {
            what: "FLV header DataOffset",
        })?;
        if data_offset < FLV_HEADER_LEN {
            return Err(RtmpError::Malformed {
                what: "FLV header DataOffset",
            });
        }
        need_in(bytes, data_offset, "FLV header")?;
        let extra = &bytes[FLV_HEADER_LEN..data_offset];
        Ok(Self {
            has_audio: flags & FLV_FLAG_AUDIO != 0,
            has_video: flags & FLV_FLAG_VIDEO != 0,
            extra,
        })
    }
}

impl<'a> Serialize for FlvHeader<'a> {
    type Error = RtmpError;

    fn serialized_len(&self) -> usize {
        FLV_HEADER_LEN + self.extra.len() + FLV_PREV_TAG_SIZE_LEN
    }

    fn serialize_into(&self, buf: &mut [u8]) -> FlvResult<usize> {
        let len = self.serialized_len();
        need_out(buf, len, "FlvHeader")?;
        let Some(out) = buf.get_mut(..len) else {
            return Err(RtmpError::from(make_output_too_small(len, buf.len())));
        };
        out.get_mut(..FLV_SIGNATURE.len())
            .unwrap_or_default()
            .copy_from_slice(&FLV_SIGNATURE);
        if let Some(b) = out.get_mut(FLV_SIGNATURE.len()) {
            *b = FLV_VERSION;
        }
        if let Some(b) = out.get_mut(FLV_SIGNATURE.len() + 1) {
            *b = self.type_flags();
        }
        let offset = fit_u32(self.data_offset(), "DataOffset")?;
        out.get_mut(5..FLV_HEADER_LEN)
            .unwrap_or_default()
            .copy_from_slice(&offset.to_be_bytes());
        let extra_start = FLV_HEADER_LEN;
        let extra_end = extra_start + self.extra.len();
        if let Some(dst) = out.get_mut(extra_start..extra_end) {
            dst.copy_from_slice(self.extra);
        }
        out.get_mut(extra_end..len)
            .unwrap_or_default()
            .copy_from_slice(&0u32.to_be_bytes());
        Ok(len)
    }
}

// ── Tag (§E.4.1) ────────────────────────────────────────────────────────

/// FLV tag `TagType` (§E.4.1), carrying the RTMP message type ids of a media
/// tag: Audio (8), Video (9) and Data-AMF0 (18) are the same three values in
/// both formats (RTMP §7.1.4, §7.1.5, §7.1.2).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TagType {
    /// Audio tag (8): `AudioTagHeader` + `AACAUDIODATA` (§E.4.2).
    Audio,
    /// Video tag (9): `VideoTagHeader` + `AVCVIDEOPACKET` (§E.4.3).
    Video,
    /// Script-data tag (18): AMF0 `onMetaData` and friends (§E.4.1).
    Script,
    /// Any other tag type byte: legal on the wire, opaque to this codec.
    Reserved(u8),
}

impl TagType {
    /// The wire byte this tag type carries (§E.4.1).
    pub fn to_byte(self) -> u8 {
        match self {
            Self::Audio => MessageTypeId::Audio.to_u8(),
            Self::Video => MessageTypeId::Video.to_u8(),
            Self::Script => MessageTypeId::DataAmf0.to_u8(),
            Self::Reserved(v) => v,
        }
    }

    /// The tag type for a wire byte: the three known types, anything else
    /// [`TagType::Reserved`].
    pub fn from_byte(byte: u8) -> Self {
        match byte {
            byte if byte == MessageTypeId::Audio.to_u8() => Self::Audio,
            byte if byte == MessageTypeId::Video.to_u8() => Self::Video,
            byte if byte == MessageTypeId::DataAmf0.to_u8() => Self::Script,
            other => Self::Reserved(other),
        }
    }

    /// The spec token for the known tag types, `"reserved"` otherwise.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Audio => "audio",
            Self::Video => "video",
            Self::Script => "script",
            Self::Reserved(_) => "reserved",
        }
    }
}

broadcast_core::impl_spec_display!(TagType, Reserved);

/// One FLV tag (§E.4.1): its header fields, body, and the `PreviousTagSize`
/// that follows it, so a single value is a self-contained slice of an FLV
/// stream.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FlvTag<'a> {
    /// `TagType` byte (§E.4.1).
    pub tag_type: TagType,
    /// Millisecond timestamp: the UI24 `Timestamp` field plus the UI8
    /// `TimestampExtended` as its top byte (§E.4.1).
    pub timestamp: u32,
    /// `StreamID` (§E.4.1), zero for every tag this crate writes.
    pub stream_id: u32,
    /// The tag's `Data` bytes (`DataSize` long).
    pub body: &'a [u8],
}

impl<'a> FlvTag<'a> {
    /// A tag on the stream every FLV stream uses (`StreamID` 0).
    pub fn new(tag_type: TagType, timestamp: u32, body: &'a [u8]) -> Self {
        Self {
            tag_type,
            timestamp,
            stream_id: FLV_STREAM_ID,
            body,
        }
    }

    /// The value of the `PreviousTagSize` field following this tag (§E.4.1):
    /// the tag's header and body, excluding that field itself.
    pub fn previous_tag_size(&self) -> FlvResult<u32> {
        fit_u32(
            FLV_TAG_HEADER_LEN.saturating_add(self.body.len()),
            "PreviousTagSize",
        )
        .map_err(Into::into)
    }

    /// The tag's declared `DataSize` (§E.4.1), read from `bytes`' first
    /// [`FLV_TAG_HEADER_LEN`] bytes — how many body bytes the tag claims,
    /// whether or not they have all arrived yet.
    ///
    /// # Errors
    /// [`RtmpError::BufferTooShort`] if `bytes` does not hold a full header.
    pub fn data_size(bytes: &'a [u8]) -> FlvResult<usize> {
        need_in(bytes, FLV_TAG_HEADER_LEN, "FLV tag header")?;
        let data_size = Reader::at(bytes, TAG_DATA_SIZE_AT).u24("FLV tag header")?;
        usize::try_from(data_size).map_err(|_| RtmpError::Malformed {
            what: "FLV tag DataSize",
        })
    }
}

impl<'a> FlvTag<'a> {
    /// Parse one tag, tolerating a wrong `PreviousTagSize` (§E.4.1 makes the field redundant: it
    /// repeats the tag's own size). The `bool` is `true` when the field was present and
    /// disagreed with the tag's size; the tag itself is decoded from its header and `DataSize`.
    ///
    /// # Errors
    /// [`RtmpError::BufferTooShort`] when the header or body has not fully arrived and
    /// [`RtmpError::Malformed`] for an unusable `DataSize`.
    pub fn parse_tolerant(bytes: &'a [u8]) -> FlvResult<(Self, bool)> {
        let FlvTagHeader {
            tag_type,
            data_size,
            timestamp,
            stream_id,
        } = FlvTagHeader::parse(bytes)?;
        let body_end = FLV_TAG_HEADER_LEN
            .checked_add(
                usize::try_from(data_size).map_err(|_| RtmpError::Malformed {
                    what: "FLV tag DataSize",
                })?,
            )
            .ok_or(RtmpError::Malformed {
                what: "FLV tag DataSize",
            })?;
        let body = bytes.get(FLV_TAG_HEADER_LEN..body_end).ok_or_else(|| {
            broadcast_core::error::BufferTooShort::new(
                body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN),
                bytes.len(),
                "FLV tag",
            )
        })?;
        let mismatch = match bytes.get(body_end..body_end + FLV_PREV_TAG_SIZE_LEN) {
            Some(trailing_bytes) => {
                let trailing = u32::from_be_bytes(trailing_bytes.try_into().map_err(|_| {
                    RtmpError::Malformed {
                        what: "FLV tag PreviousTagSize",
                    }
                })?);
                let expected = u32::try_from(body_end).map_err(|_| RtmpError::Malformed {
                    what: "FLV tag PreviousTagSize",
                })?;
                trailing != expected
            }
            None => false,
        };
        Ok((
            Self {
                tag_type,
                timestamp,
                stream_id,
                body,
            },
            mismatch,
        ))
    }
}

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

    fn parse(bytes: &'a [u8]) -> FlvResult<Self> {
        let (tag, mismatch) = Self::parse_tolerant(bytes)?;
        if mismatch {
            return Err(RtmpError::Malformed {
                what: "FLV tag PreviousTagSize",
            });
        }
        Ok(tag)
    }
}

/// The 11-byte tag header of a tag whose body may not have arrived yet
/// (§E.4.1): `TagType`, `DataSize`, `Timestamp` + `TimestampExtended` and
/// `StreamID`, without the body — what an incremental reader needs to know how
/// many bytes the whole tag takes before it can decode one.
///
/// `FlvTag::parse` and the tolerant walk both read the header through here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FlvTagHeader {
    /// `TagType` byte (§E.4.1).
    pub tag_type: TagType,
    /// `DataSize` (§E.4.1): the body length that follows the header.
    pub data_size: u32,
    /// Millisecond timestamp: the UI24 `Timestamp` plus the UI8
    /// `TimestampExtended` as its top byte (§E.4.1).
    pub timestamp: u32,
    /// `StreamID` (§E.4.1).
    pub stream_id: u32,
}

impl FlvTagHeader {
    /// The header of the tag starting at the front of `bytes`.
    ///
    /// # Errors
    /// [`RtmpError::BufferTooShort`] when fewer than [`FLV_TAG_HEADER_LEN`]
    /// bytes are present.
    pub fn parse(bytes: &[u8]) -> FlvResult<Self> {
        need_in(bytes, FLV_TAG_HEADER_LEN, "FLV tag header")?;
        let field = |at: usize| bytes.get(at).copied().unwrap_or_default();
        let data_size = Reader::at(bytes, TAG_DATA_SIZE_AT).u24("FLV tag header")?;
        let ts_low24 = Reader::at(bytes, TAG_TIMESTAMP_AT).u24("FLV tag header")?;
        let ts_extended = u32::from(field(TAG_TIMESTAMP_EXTENDED_AT));
        let stream_id = Reader::at(bytes, TAG_STREAM_ID_AT).u24("FLV tag header")?;
        Ok(Self {
            tag_type: TagType::from_byte(field(0)),
            data_size,
            timestamp: ts_low24 | (ts_extended << FLV_TIMESTAMP_EXTENDED_SHIFT),
            stream_id,
        })
    }

    /// Bytes of the whole tag this header announces: header, body and the
    /// trailing `PreviousTagSize` (§E.4.1).
    #[must_use]
    pub fn total_len(&self) -> usize {
        let body = usize::try_from(self.data_size).unwrap_or(usize::MAX);
        FLV_TAG_HEADER_LEN
            .saturating_add(body)
            .saturating_add(FLV_PREV_TAG_SIZE_LEN)
    }
}

impl Serialize for FlvTagHeader {
    type Error = RtmpError;

    fn serialized_len(&self) -> usize {
        FLV_TAG_HEADER_LEN
    }

    fn serialize_into(&self, buf: &mut [u8]) -> FlvResult<usize> {
        need_out(buf, FLV_TAG_HEADER_LEN, "FlvTagHeader")?;
        let mut w = Writer::new(buf);
        w.u8(self.tag_type.to_byte(), "FLV tag TagType")?;
        w.u24::<RtmpError>(self.data_size, "FLV tag DataSize")?;
        w.u24::<RtmpError>(self.timestamp & TIMESTAMP_LOW24_MASK, "FLV tag Timestamp")?;
        let extended = self.timestamp >> FLV_TIMESTAMP_EXTENDED_SHIFT;
        let Some(extended) = u8::try_from(extended).ok() else {
            return Err(RtmpError::Malformed {
                what: "FLV tag TimestampExtended",
            });
        };
        w.u8(extended, "FLV tag TimestampExtended")?;
        w.u24::<RtmpError>(self.stream_id, "FLV tag StreamID")?;
        Ok(FLV_TAG_HEADER_LEN)
    }
}

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

    fn serialized_len(&self) -> usize {
        FLV_TAG_HEADER_LEN
            .saturating_add(self.body.len())
            .saturating_add(FLV_PREV_TAG_SIZE_LEN)
    }

    fn serialize_into(&self, buf: &mut [u8]) -> FlvResult<usize> {
        let len = self.serialized_len();
        need_out(buf, len, "FlvTag")?;
        let data_size = fit_u24(self.body.len(), "DataSize")?;
        let mut w = Writer::new(buf);
        w.u8(self.tag_type.to_byte(), "FLV tag TagType")?;
        w.u24::<RtmpError>(data_size, "FLV tag DataSize")?;
        w.u24::<RtmpError>(self.timestamp & TIMESTAMP_LOW24_MASK, "FLV tag Timestamp")?;
        let timestamp_extended = self.timestamp >> FLV_TIMESTAMP_EXTENDED_SHIFT;
        let Some(extended) = u8::try_from(timestamp_extended).ok() else {
            return Err(RtmpError::Malformed {
                what: "FLV tag TimestampExtended",
            });
        };
        w.u8(extended, "FLV tag TimestampExtended")?;
        w.u24::<RtmpError>(self.stream_id, "FLV tag StreamID")?;
        let previous_tag_size = self.previous_tag_size()?;
        w.bytes(self.body, "FLV tag body")?;
        w.u32(previous_tag_size, "FLV tag PreviousTagSize")?;
        Ok(len)
    }
}

/// Offset of `DataSize` inside a tag header (§E.4.1).
const TAG_DATA_SIZE_AT: usize = 1;
/// Offset of the UI24 low `Timestamp` inside a tag header (§E.4.1).
const TAG_TIMESTAMP_AT: usize = 4;
/// Offset of `TimestampExtended` inside a tag header (§E.4.1).
const TAG_TIMESTAMP_EXTENDED_AT: usize = 7;
/// Offset of `StreamID` inside a tag header (§E.4.1).
const TAG_STREAM_ID_AT: usize = 8;
/// Byte width of a u32 field.
const U32_LEN: usize = core::mem::size_of::<u32>();
/// The low 24 bits of a tag's `Timestamp` (§E.4.1), the part the UI24 field
/// carries.
const TIMESTAMP_LOW24_MASK: u32 = 0x00FF_FFFF;

// ── Tag walk ────────────────────────────────────────────────────────────

/// The tags of an FLV stream, in order, starting at `header`'s first tag.
///
/// Strict: no resynchronisation. Every item is exactly one tag (header, body
/// and `PreviousTagSize`); a trailing run too short to be a complete tag is
/// yielded as an error item and ends the walk.
pub fn tags<'a>(input: &'a [u8], header: &FlvHeader<'a>) -> Tags<'a> {
    Tags {
        input,
        offset: header.first_tag_offset(),
    }
}

/// Iterator over an FLV stream's tags — see [`tags`].
#[derive(Debug, Clone)]
pub struct Tags<'a> {
    input: &'a [u8],
    offset: usize,
}

impl<'a> Iterator for Tags<'a> {
    type Item = FlvResult<FlvTag<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        let rest = self.input.get(self.offset..)?;
        if rest.is_empty() {
            return None;
        }
        let tag = match FlvTag::parse(rest) {
            Ok(tag) => tag,
            Err(err) => {
                self.offset = self.input.len();
                return Some(Err(err));
            }
        };
        self.offset = self.offset.saturating_add(tag.serialized_len());
        Some(Ok(tag))
    }
}

// ── Tolerant walk (resynchronising) ─────────────────────────────────────

/// A tag header at `off` that is structurally plausible: a readable header,
/// the always-zero 24-bit `StreamID` (§E.4.1) and, when `known_type`, one of
/// the tag types a media demuxer reads. Unknown types are legal (a walker
/// skips them leniently), so the chain check along the stream accepts them;
/// only a *resync candidate*, picked out of arbitrary bytes, is held to a
/// known type.
fn plausible_tag_header(input: &[u8], off: usize, known_type: bool) -> bool {
    off.saturating_add(FLV_TAG_HEADER_LEN) <= input.len()
        && (!known_type
            || [
                MessageTypeId::Audio,
                MessageTypeId::Video,
                MessageTypeId::DataAmf0,
            ]
            .contains(&MessageTypeId::from_u8(input[off])))
        && input[off + TAG_STREAM_ID_AT..off + FLV_TAG_HEADER_LEN] == [0, 0, 0]
}

/// The `DataSize` of the tag whose header starts at `off` (the caller has
/// checked that the header is readable).
fn tag_data_size(input: &[u8], off: usize) -> usize {
    FlvTagHeader::parse(&input[off..])
        .ok()
        .and_then(|header| usize::try_from(header.data_size).ok())
        .unwrap_or_default()
}

/// Whether the tag starting at `off` is followed by a consistent chain: its
/// body fits, and what follows it is the end of the buffer or another
/// plausible tag header.
fn tag_chain_holds(input: &[u8], off: usize, known_type: bool) -> bool {
    if !plausible_tag_header(input, off, known_type) {
        return false;
    }
    let Some(body_end) = off
        .saturating_add(FLV_TAG_HEADER_LEN)
        .checked_add(tag_data_size(input, off))
    else {
        return false;
    };
    if body_end > input.len() {
        return false;
    }
    let next = body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN);
    next.saturating_add(FLV_TAG_HEADER_LEN) > input.len()
        || plausible_tag_header(input, next, false)
}

/// First offset at or after `from` where a consistent chain of known-type tags
/// starts.
fn resync_tag(input: &[u8], from: usize) -> Option<usize> {
    (from..input.len()).find(|&at| tag_chain_holds(input, at, true))
}

/// An FLV stream walked tolerantly: every tag, the damaged spans skipped, and
/// whether the input ended on a short tail — see [`tags_resync`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResyncWalk<'a> {
    /// The complete tags, in order, with their offsets.
    pub tags: Vec<(usize, FlvTag<'a>)>,
    /// Offsets of the spans whose tag framing was damaged and skipped.
    pub damaged: Vec<usize>,
    /// Offsets of the tags kept although their `PreviousTagSize` disagreed with their size.
    pub bad_previous_tag_sizes: Vec<usize>,
    /// `Some` when the input ends mid-tag: the tag it stopped at, and the
    /// bytes that tag would need against the bytes actually present.
    pub truncated_tail: Option<(usize, usize, usize)>,
}

impl ResyncWalk<'_> {
    /// One report per skip this walk made: a damaged span
    /// ([`broadcast_core::damage::DamageKind::Resynchronised`] over the bytes
    /// jumped) and a truncated tail
    /// ([`broadcast_core::damage::DamageKind::InputTruncated`]). A caller that
    /// publishes damage reports hands these on rather than leaving
    /// [`Self::damaged`] and [`Self::truncated_tail`] unread.
    #[must_use]
    pub fn damage(&self) -> Vec<broadcast_core::damage::Damage> {
        let mut reports =
            Vec::with_capacity(self.damaged.len() + self.bad_previous_tag_sizes.len() + 1);
        for (index, start) in self.damaged.iter().enumerate() {
            let end = self
                .damaged
                .get(index + 1)
                .copied()
                .or_else(|| self.tags.get(index).map(|(offset, _)| *offset))
                .unwrap_or(*start);
            let len = end.saturating_sub(*start) as u64;
            reports.push(
                broadcast_core::damage::Damage::new(
                    broadcast_core::damage::DamageKind::Resynchronised,
                    broadcast_core::damage::Severity::Degraded,
                    "FLV tag",
                )
                .with_byte_range(broadcast_core::range::ByteRange::new(*start as u64, len)),
            );
        }
        for offset in &self.bad_previous_tag_sizes {
            reports.push(
                broadcast_core::damage::Damage::new(
                    broadcast_core::damage::DamageKind::MetadataSkipped,
                    broadcast_core::damage::Severity::Informational,
                    "FLV PreviousTagSize",
                )
                .with_byte_range(broadcast_core::range::ByteRange::new(
                    *offset as u64,
                    FLV_TAG_HEADER_LEN as u64,
                )),
            );
        }
        if let Some((start, need, have)) = self.truncated_tail {
            let missing = need.saturating_sub(have) as u64;
            reports.push(
                broadcast_core::damage::Damage::new(
                    broadcast_core::damage::DamageKind::InputTruncated,
                    broadcast_core::damage::Severity::Degraded,
                    "FLV tag",
                )
                .with_byte_range(broadcast_core::range::ByteRange::new(start as u64, missing)),
            );
        }
        reports
    }
}

/// What an incremental caller should do with the bytes at the front of its
/// buffer — see [`resync_decision`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResyncDecision {
    /// The front is the start of a consistent tag chain: parse it normally.
    Tag,
    /// More input is needed before the front can be decided. The buffer must
    /// hold at least this many bytes in total.
    Need(usize),
    /// The front bytes are damaged: skip this many and decide again. The skip
    /// is one span, reported once by the caller.
    Skip(usize),
}

/// Decide what to do with the bytes at the front of a streaming buffer, using
/// the same consistency rule [`tags_resync`] walks with.
///
/// Unlike [`tags_resync`], nothing is retained here: the caller keeps the
/// buffer and acts on the decision, so a streaming demux can resynchronise
/// while holding at most the bytes one candidate tag's own header declares.
#[must_use]
pub fn resync_decision(input: &[u8], at_eof: bool) -> ResyncDecision {
    if input.len() < FLV_TAG_HEADER_LEN {
        return ResyncDecision::Need(FLV_TAG_HEADER_LEN);
    }
    // A complete tag whose own trailing `PreviousTagSize` agrees with its
    // header is whole: it needs no second opinion from the tag after it, so a
    // streaming caller does not have to wait for that tag's header.
    if let Ok(header) = FlvTagHeader::parse(input) {
        let total = header.total_len();
        if input.len() >= total && FlvTag::parse(&input[..total]).is_ok() {
            return ResyncDecision::Tag;
        }
    }
    if tag_chain_holds(input, 0, false) {
        if !at_eof {
            // The chain "holds" here only because the header after this tag has
            // not arrived yet. Waiting for it is what tells a real tag from a
            // damaged one whose declared body runs into the next tag.
            let next = FLV_TAG_HEADER_LEN
                .saturating_add(tag_data_size(input, 0))
                .saturating_add(FLV_PREV_TAG_SIZE_LEN);
            if next.saturating_add(FLV_TAG_HEADER_LEN) > input.len() {
                return ResyncDecision::Need(next.saturating_add(FLV_TAG_HEADER_LEN));
            }
        }
        return ResyncDecision::Tag;
    }
    // A plausible header whose own body has not fully arrived is a tag still
    // being read, not damage: wait for exactly that body. At end of input it
    // cannot arrive, so the front is damaged and the scan below decides.
    if plausible_tag_header(input, 0, false) {
        let body_end = FLV_TAG_HEADER_LEN.saturating_add(tag_data_size(input, 0));
        if body_end > input.len() && !at_eof {
            return ResyncDecision::Need(body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN));
        }
    }
    for at in 1..input.len() {
        if !plausible_tag_header(input, at, true) {
            continue;
        }
        let body_end = at
            .saturating_add(FLV_TAG_HEADER_LEN)
            .saturating_add(tag_data_size(input, at));
        if body_end > input.len() {
            if at_eof {
                continue;
            }
            // An earlier plausible tag may be the resync point; a later
            // candidate must not preempt it, so wait for this one's body.
            return ResyncDecision::Need(body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN));
        }
        if !at_eof
            && body_end
                .saturating_add(FLV_PREV_TAG_SIZE_LEN)
                .saturating_add(FLV_TAG_HEADER_LEN)
                > input.len()
        {
            // The candidate's body is complete, but the header that would
            // prove its chain has not fully arrived: accepting it now could
            // lock onto a stray byte pattern inside a damaged tag, and a LATER
            // candidate must not preempt this earlier one (a whole-buffer walk
            // decides the earliest first). Wait for this one.
            return ResyncDecision::Need(
                body_end
                    .saturating_add(FLV_PREV_TAG_SIZE_LEN)
                    .saturating_add(FLV_TAG_HEADER_LEN),
            );
        }
        if tag_chain_holds(input, at, true) {
            return ResyncDecision::Skip(at);
        }
    }
    if at_eof {
        // No consistent tag chain anywhere in what is left: the tail is
        // damaged. Consume it (keeping less than one tag header so the next
        // decision terminates) and let the caller report the span.
        return ResyncDecision::Skip(input.len().saturating_sub(FLV_TAG_HEADER_LEN - 1));
    }
    ResyncDecision::Need(input.len().saturating_add(1))
}

/// Walk an FLV stream's tags tolerantly, from `header`'s first tag.
///
/// Unlike the strict [`tags`], a stream whose framing is damaged part-way
/// still yields the tags after the damage: a span whose tag chain does not hold
/// is skipped to the next consistent chain of known-type tags and reported in
/// [`ResyncWalk::damaged`], and a final tag whose body overruns the input stops
/// the walk (reported in [`ResyncWalk::truncated_tail`]) rather than losing the
/// good prefix. Two shapes are not truncation: a final tag whose body is
/// complete but whose 4-byte `PreviousTagSize` is missing (§E.4.1 makes that
/// field redundant — it repeats the tag's own size) is kept and the walk ends
/// cleanly, and a header too short to read at the very end of the input is
/// simply the end of the walk.
///
/// # Errors
/// [`RtmpError::BufferTooShort`] when `input` is shorter than the header and
/// its `PreviousTagSize0`, and when the *first* tag is already incomplete (that
/// is not a recoverable tail: there is nothing complete to return).
pub fn tags_resync<'a>(input: &'a [u8], header: &FlvHeader<'a>) -> FlvResult<ResyncWalk<'a>> {
    need_in(
        input,
        FLV_HEADER_LEN.saturating_add(FLV_PREV_TAG_SIZE_LEN),
        "FLV header",
    )?;
    let mut off = header.first_tag_offset();
    let mut walk = ResyncWalk {
        tags: Vec::new(),
        damaged: Vec::new(),
        bad_previous_tag_sizes: Vec::new(),
        truncated_tail: None,
    };
    while off.saturating_add(FLV_TAG_HEADER_LEN) <= input.len() {
        if !tag_chain_holds(input, off, false)
            && let Some(next) = resync_tag(input, off + 1)
        {
            walk.damaged.push(off);
            off = next;
            continue;
        }
        let Some(body_end) = off
            .saturating_add(FLV_TAG_HEADER_LEN)
            .checked_add(tag_data_size(input, off))
        else {
            return Err(RtmpError::Malformed {
                what: "FLV tag DataSize",
            });
        };
        if body_end > input.len() {
            let need = body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN);
            if walk.tags.is_empty() && walk.damaged.is_empty() {
                return Err(RtmpError::BufferTooShort(
                    broadcast_core::error::BufferTooShort::new(need, input.len(), "FLV tag body"),
                ));
            }
            walk.truncated_tail = Some((off, need, input.len().saturating_sub(off)));
            return Ok(walk);
        }
        let codec_end = body_end
            .saturating_add(FLV_PREV_TAG_SIZE_LEN)
            .min(input.len());
        let (tag, mismatch) =
            FlvTag::parse_tolerant(input.get(off..codec_end).unwrap_or_default())?;
        if mismatch {
            walk.bad_previous_tag_sizes.push(off);
        }
        walk.tags.push((off, tag));
        if body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN) > input.len() {
            return Ok(walk);
        }
        off = body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN);
    }
    Ok(walk)
}

// ── Session writer ──────────────────────────────────────────────────────

/// Builds the FLV byte stream of one RTMP session: the first tag is prefixed
/// with the file header ([`FlvHeader`] + `PreviousTagSize0`), every tag carries
/// its own header and `PreviousTagSize`, so concatenating every returned chunk
/// in order yields a valid FLV stream.
#[derive(Debug, Default)]
pub(crate) struct FlvTagWriter {
    header_sent: bool,
}

impl FlvTagWriter {
    /// One FLV tag for a media or script message body (file header first time).
    ///
    /// # Errors
    /// [`RtmpError::FieldOverflow`] if `payload` does not fit the tag's 24-bit
    /// `DataSize`, or the session's FLV bytes cannot be built.
    pub(crate) fn tag(
        &mut self,
        tag_type: MessageTypeId,
        timestamp: u32,
        payload: &[u8],
    ) -> FlvResult<Vec<u8>> {
        let payload = if tag_type == MessageTypeId::DataAmf0 {
            strip_set_data_frame(payload)
        } else {
            payload
        };
        let mut flv = if self.header_sent {
            Vec::new()
        } else {
            self.header_sent = true;
            FlvHeader::new(true, true).try_to_bytes()?
        };
        let tag = FlvTag::new(TagType::from_byte(tag_type.to_u8()), timestamp, payload);
        flv.extend_from_slice(&tag.try_to_bytes()?);
        Ok(flv)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ids::{ChunkStreamId, MessageStreamId, Timestamp};

    fn header(tag_type: TagType, timestamp: u32, data_size: u32) -> FlvTagHeader {
        FlvTagHeader {
            tag_type,
            data_size,
            timestamp,
            stream_id: 0,
        }
    }

    fn tag(tag_type: TagType, timestamp: u32, body: &[u8]) -> Vec<u8> {
        let header = header(
            tag_type,
            timestamp,
            u32::try_from(body.len()).expect("fits"),
        );
        let mut out = vec![0u8; header.total_len()];
        header
            .serialize_into(&mut out[..FLV_TAG_HEADER_LEN])
            .unwrap();
        out[FLV_TAG_HEADER_LEN..FLV_TAG_HEADER_LEN + body.len()].copy_from_slice(body);
        let previous = u32::try_from(FLV_TAG_HEADER_LEN + body.len()).expect("fits");
        out[FLV_TAG_HEADER_LEN + body.len()..].copy_from_slice(&previous.to_be_bytes());
        out
    }

    fn aggregate_msg(timestamp: u32, payload: Vec<u8>) -> Message {
        Message {
            chunk_stream_id: ChunkStreamId::new(3),
            timestamp: Timestamp::from_millis(timestamp),
            message_type_id: MessageTypeId::Aggregate,
            message_stream_id: MessageStreamId::new(1),
            payload,
        }
    }

    fn sub_message(tag_type: MessageTypeId, timestamp: u32, body: &[u8]) -> Vec<u8> {
        let mut out = vec![0u8; AGG_SUB_MESSAGE_HEADER_LEN];
        out[0] = tag_type.to_u8();
        let size = u32::try_from(body.len()).expect("fits");
        out[1..4].copy_from_slice(&size.to_be_bytes()[1..]);
        out[4..7].copy_from_slice(&timestamp.to_be_bytes()[1..]);
        out[7] = u8::try_from(timestamp >> AGG_TIMESTAMP_EXTENDED_SHIFT).expect("fits");
        out.extend_from_slice(body);
        out.extend_from_slice(
            &u32::try_from(AGG_SUB_MESSAGE_HEADER_LEN + body.len())
                .expect("fits")
                .to_be_bytes(),
        );
        out
    }

    #[test]
    fn an_aggregate_delivers_only_audio_video_and_data_sub_messages() {
        let mut payload = Vec::new();
        payload.extend_from_slice(&sub_message(MessageTypeId::Audio, 0, &[1]));
        payload.extend_from_slice(&sub_message(MessageTypeId::CommandAmf0, 1, &[2]));
        payload.extend_from_slice(&sub_message(MessageTypeId::Aggregate, 2, &[3]));
        payload.extend_from_slice(&sub_message(MessageTypeId::SetChunkSize, 3, &[4]));
        payload.extend_from_slice(&sub_message(MessageTypeId::Video, 4, &[5]));
        let mut delivered = Vec::new();
        let mut damage = Vec::new();
        unpack_aggregate(&aggregate_msg(0, payload), &mut damage, |tt, ts, _| {
            delivered.push((tt, ts));
            Ok(())
        })
        .unwrap();
        assert_eq!(
            delivered,
            [(MessageTypeId::Audio, 0), (MessageTypeId::Video, 4)]
        );
        assert_eq!(damage.len(), 3);
        assert!(
            damage
                .iter()
                .all(|d| d.kind() == broadcast_core::damage::DamageKind::MetadataUninterpreted)
        );
    }

    #[test]
    fn aggregate_rebases_extended_sub_message_timestamps() {
        let big = vec![0xB0u8; 65_837];
        let mut payload = Vec::new();
        payload.extend_from_slice(&sub_message(
            MessageTypeId::Audio,
            0x0000_0010,
            &[0xA1, 0xA2],
        ));
        payload.extend_from_slice(&sub_message(MessageTypeId::Video, 0x0100_0020, &big));
        payload.extend_from_slice(&sub_message(MessageTypeId::DataAmf0, 0x0000_0030, &[0xC1]));

        let mut delivered = Vec::new();
        let mut damage = Vec::new();
        unpack_aggregate(
            &aggregate_msg(0x0100_0100, payload),
            &mut damage,
            |tt, ts, body| {
                delivered.push((tt, ts, body.to_vec()));
                Ok(())
            },
        )
        .expect("well-formed aggregate");
        assert!(damage.is_empty(), "a well-formed aggregate reports nothing");
        assert_eq!(delivered.len(), 3);
        assert_eq!(
            delivered[0],
            (MessageTypeId::Audio, 0x0100_0100, vec![0xA1, 0xA2])
        );
        assert_eq!(delivered[1].0, MessageTypeId::Video);
        assert_eq!(delivered[1].1, 0x0200_0110);
        assert_eq!(delivered[1].2.len(), 65_837);
        assert_eq!(delivered[1].2[0], 0xB0);
        assert_eq!(
            delivered[2],
            (MessageTypeId::DataAmf0, 0x0100_0120, vec![0xC1])
        );
    }

    /// The sub-message run past the aggregate's end is malformed, but it no
    /// longer ends the session: the good sub-messages before it were already
    /// delivered and the rest is reported.
    #[test]
    fn aggregate_header_exactly_at_the_end_is_malformed_as_data_overrun() {
        let mut payload = sub_message(MessageTypeId::Audio, 0, &[1]);
        payload.extend_from_slice(&[0u8; AGG_SUB_MESSAGE_HEADER_LEN]);
        let mut damage = Vec::new();
        let mut delivered = 0usize;
        unpack_aggregate(&aggregate_msg(0, payload), &mut damage, |_, _, _| {
            delivered += 1;
            Ok(())
        })
        .expect("a malformed sub-message must not end the session");
        assert_eq!(delivered, 1, "the good sub-message before it is delivered");
        assert_eq!(damage.len(), 1, "the overrunning sub-message is reported");
        assert_eq!(
            damage[0].kind(),
            broadcast_core::damage::DamageKind::MediaUnitDropped
        );
    }

    #[test]
    fn aggregate_truncated_into_a_sub_message_is_malformed() {
        let mut payload = sub_message(MessageTypeId::Audio, 0, &[1, 2, 3]);
        let full_len = payload.len();
        payload.truncate(full_len - 1);
        let mut damage = Vec::new();
        assert!(
            unpack_aggregate(&aggregate_msg(0, payload), &mut damage, |_, _, _| Ok(())).is_ok()
        );
        assert_eq!(damage.len(), 1);

        let mut payload = sub_message(MessageTypeId::Audio, 0, &[1, 2, 3]);
        payload.extend_from_slice(&[0xFF, 0xFF, 0xFF]);
        let mut damage = Vec::new();
        assert!(
            unpack_aggregate(&aggregate_msg(0, payload), &mut damage, |_, _, _| Ok(())).is_ok()
        );
        assert_eq!(damage.len(), 1);
    }

    #[test]
    fn tag_type_from_byte_maps_the_three_media_types() {
        assert_eq!(TagType::from_byte(8), TagType::Audio);
        assert_eq!(TagType::from_byte(9), TagType::Video);
        assert_eq!(TagType::from_byte(18), TagType::Script);
        assert_eq!(TagType::from_byte(0), TagType::Reserved(0));
        assert_eq!(TagType::Audio.name(), "audio");
        assert_eq!(TagType::Video.name(), "video");
        assert_eq!(TagType::Script.name(), "script");
        assert_eq!(TagType::Reserved(0).name(), "reserved");
    }

    #[test]
    fn tag_header_lengths_and_bytes_are_exact() {
        let header = header(TagType::Audio, 0x0A0B_0C0D, 0x01_0203);
        assert_eq!(header.total_len(), 11 + 0x010203 + 4);
        assert_eq!(header.serialized_len(), 11);
        let mut bytes = [0u8; 11];
        assert_eq!(header.serialize_into(&mut bytes).unwrap(), 11);
        assert_eq!(
            bytes,
            [8, 0x01, 0x02, 0x03, 0x0B, 0x0C, 0x0D, 0x0A, 0, 0, 0]
        );
    }

    #[test]
    fn resync_decision_keeps_waits_and_skips_to_the_same_chain() {
        // A whole tag at the front is kept, with or without the header that
        // follows it.
        let good = tag(TagType::Audio, 0, b"abc");
        assert_eq!(resync_decision(&good, false), ResyncDecision::Tag);
        assert_eq!(resync_decision(&good, true), ResyncDecision::Tag);
        // A partial header just asks for the header bytes.
        assert_eq!(
            resync_decision(&good[..5], false),
            ResyncDecision::Need(FLV_TAG_HEADER_LEN)
        );
        // Garbage before a consistent chain is one span to skip up to it.
        let mut damaged = vec![0xFFu8; 7];
        damaged.extend_from_slice(&good);
        assert_eq!(
            resync_decision(&damaged, false),
            ResyncDecision::Need(7 + 11 + 3 + FLV_PREV_TAG_SIZE_LEN + FLV_TAG_HEADER_LEN),
            "the candidate's chain needs its following header before it is trusted"
        );
        assert_eq!(resync_decision(&damaged, true), ResyncDecision::Skip(7));
        // A plausible header whose declared body has not arrived asks for the
        // bytes that body needs, not a skip.
        let declared = tag(TagType::Video, 0, &[0u8; 40]);
        assert_eq!(
            resync_decision(&declared[..FLV_TAG_HEADER_LEN + 4], false),
            ResyncDecision::Need(FLV_TAG_HEADER_LEN + 40 + FLV_PREV_TAG_SIZE_LEN)
        );
    }

    #[test]
    fn reserved_tag_type_is_plausible_only_inside_a_chain() {
        let bytes = tag(TagType::Reserved(200), 0, b"abc");
        assert!(
            plausible_tag_header(&bytes, 0, false),
            "an unknown type is legal in a chain"
        );
        assert!(
            !plausible_tag_header(&bytes, 0, true),
            "a resync candidate must be a known media type"
        );
    }

    #[test]
    fn a_chain_whose_second_header_is_implausible_does_not_hold() {
        let mut bytes = tag(TagType::Audio, 0, b"abc");
        bytes.extend_from_slice(&[0xFF; 20]);
        assert!(!tag_chain_holds(&bytes, 0, false));
        assert!(!tag_chain_holds(&bytes, 0, true));
    }

    #[test]
    fn a_chain_ending_exactly_after_the_body_holds() {
        let header = header(TagType::Audio, 0, 3);
        let mut bytes = vec![0u8; FLV_TAG_HEADER_LEN];
        header.serialize_into(&mut bytes).unwrap();
        bytes.extend_from_slice(b"abc");
        assert!(tag_chain_holds(&bytes, 0, false));
    }

    #[test]
    fn a_chain_whose_next_header_is_exactly_at_the_end_with_eleven_bytes() {
        let mut bytes = tag(TagType::Audio, 0, b"abc");
        bytes.extend_from_slice(&[0x12, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]);
        assert_eq!(bytes.len(), 18 + FLV_TAG_HEADER_LEN);
        assert!(
            !tag_chain_holds(&bytes, 0, false),
            "an implausible header at the very end breaks the chain"
        );
    }

    #[test]
    fn a_final_tag_body_reaching_the_end_without_previous_size_is_kept() {
        let flv_header = FlvHeader::new(true, true);
        let mut input = flv_header.try_to_bytes().unwrap();
        input.extend_from_slice(&tag(TagType::Audio, 0, b"abc"));
        let tail_header = header(TagType::Video, 1, 2);
        let mut tail = vec![0u8; FLV_TAG_HEADER_LEN];
        tail_header.serialize_into(&mut tail).unwrap();
        tail.extend_from_slice(&[0xBB, 0xCC]);
        input.extend_from_slice(&tail);

        let walk = tags_resync(&input, &flv_header).expect("tolerant walk");
        assert_eq!(walk.tags.len(), 2);
        assert!(walk.truncated_tail.is_none());
    }

    #[test]
    fn tags_resync_starts_the_search_after_the_damaged_offset() {
        let flv_header = FlvHeader::new(true, true);
        let mut input = flv_header.try_to_bytes().unwrap();
        input.extend_from_slice(&tag(TagType::Audio, 0, &[0u8; 7]));
        // The previous tag's PreviousTagSize is 18, whose last byte is the
        // Data-AMF0 type id: a plausible tag starts one byte before the
        // damaged offset. Only a search that starts at off + 1 skips it.
        input.extend_from_slice(&[
            0, 0, 1, // DataSize 1
            0, 0, 0, // Timestamp 0
            0, // TimestampExtended
            0, 0, 0, // StreamID
            0, // body
            0, 0, 0, 12, // PreviousTagSize = 11 + 1
        ]);

        let walk = tags_resync(&input, &flv_header).expect("tolerant walk");
        assert_eq!(walk.tags.len(), 1);
        assert!(walk.damaged.is_empty());
        assert!(walk.truncated_tail.is_some());
    }

    #[test]
    fn tags_resync_recovers_after_garbage() {
        let header = FlvHeader::new(true, true);
        let mut input = header.try_to_bytes().unwrap();
        let mut offsets = Vec::new();
        for i in 0..10u32 {
            offsets.push(input.len());
            input.extend_from_slice(&tag(
                TagType::Audio,
                i,
                &[u8::try_from(i).expect("fits"), 0xEE],
            ));
            if i == 3 {
                input.extend_from_slice(&[0xFF; 37]);
            }
        }

        let walk = tags_resync(&input, &header).expect("tolerant walk");
        // The tag whose chain runs into the damage is skipped too, so the
        // three tags before it plus tags 5..10 come back.
        assert_eq!(
            walk.tags.len(),
            9,
            "offsets {:?} damaged {:?}",
            walk.tags.iter().map(|(o, _)| *o).collect::<Vec<_>>(),
            walk.damaged
        );
        assert_eq!(walk.damaged, vec![offsets[3]]);
        assert_eq!(walk.tags[3].0, offsets[4]);
        assert_eq!(walk.tags[3].1.timestamp, 4);
        assert_eq!(walk.tags[8].0, offsets[9]);
        assert_eq!(walk.tags[8].1.timestamp, 9);
    }
}