rtmp-runtime 0.11.0

Sans-IO RTMP 1.0 (Adobe Real-Time Messaging Protocol) ingest session engine — a driveable server-side publish state machine 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
//! RTMP client session engine — `connect` → `createStream` → `publish`
//! (Adobe RTMP 1.0 §7.2, `NetConnection`/`NetStream` commands).
//!
//! [`ClientSession`] mirrors [`crate::server::ServerSession`]: a sans-IO
//! state machine for the **client publish** role. Feed inbound bytes via
//! [`ClientSession::handle_data`], get back outbound bytes + typed
//! [`ClientEvent`]s. Auto-advances: a successful `connect` `_result`
//! automatically emits `createStream`, and a successful `createStream`
//! `_result` emits `publish`.

use broadcast_common::error::BufferTooShort;
use broadcast_common::len::need_in;
use broadcast_common::{Parse, Serialize};

use crate::RtmpError;
use crate::amf0::{Amf0Value, Command};
use crate::chunk::{ChunkAssembler, ChunkWriter, DEFAULT_MAX_IN_PROGRESS_BYTES, Message};
use crate::flv::{FlvTagWriter, unpack_aggregate};
use crate::handshake::{
    EchoPacket, HANDSHAKE_PACKET_LEN, HandshakePacket, RTMP_VERSION, Version, default_random_fill,
};
use crate::ids::{ChunkStreamId, MessageStreamId, SequenceNumber, Timestamp};
use crate::message::{ChunkSize, MessageTypeId, ProtocolControl, UserControl};
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

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

const COMMAND_CHUNK_STREAM_ID: u32 = 3;
const VERSION_LEN: usize = 1;
/// `flashVer` announced in `connect`: the Flash Media Live Encoder
/// identity that ingest services key their publisher-compatibility
/// handling on (what ffmpeg/OBS announce; #1108/RTMP-W9).
const FLASH_VER: &str = "FMLE/3.0 (compatible; rtmp-runtime)";
/// FMLE-style publish preamble commands sent before `createStream`
/// (Adobe FMLE publish sequence, as ffmpeg's `rtmpproto` emits it).
const CMD_RELEASE_STREAM: &str = "releaseStream";
const CMD_FC_PUBLISH: &str = "FCPublish";
/// `play` Start argument (§7.2.2.1): `-2` plays the live stream of that name, else a recorded
/// one, else waits for a live one.
const PLAY_START_LIVE_OR_RECORDED: f64 = -2.0;
/// Default playback buffer length announced with SetBufferLength before `play` (§6.7).
pub const DEFAULT_PLAY_BUFFER: core::time::Duration = core::time::Duration::from_secs(3);
const STATUS_PLAY_START: &str = "NetStream.Play.Start";
const STATUS_PLAY_STOP: &str = "NetStream.Play.Stop";
const STATUS_PLAY_COMPLETE: &str = "NetStream.Play.Complete";
const STATUS_PLAY_STREAM_NOT_FOUND: &str = "NetStream.Play.StreamNotFound";
const STATUS_PLAY_FAILED: &str = "NetStream.Play.Failed";
const STATUS_LEVEL_ERROR: &str = "error";

/// What a [`ClientSession`] does after `connect` and `createStream`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ClientMode {
    /// `publish` a stream (§7.2.2.6): the session sends audio, video and metadata.
    #[default]
    Publish,
    /// `play` a stream (§7.2.2.1): the session receives audio, video and data.
    Play,
}

impl ClientMode {
    /// The NetStream command this mode ends in.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Publish => "publish",
            Self::Play => "play",
        }
    }
}

broadcast_common::impl_spec_display!(ClientMode);

/// Configuration for a [`ClientSession`].
#[non_exhaustive]
#[derive(Clone)]
pub struct RtmpClientConfig {
    /// Publish (default) or play.
    pub mode: ClientMode,
    /// Playback buffer length announced to the server before `play` (§6.7 SetBufferLength),
    /// sent as whole milliseconds on the wire. Play mode only.
    pub play_buffer: core::time::Duration,
    /// Outbound chunk size (§5.4.1).
    pub chunk_size: u32,
    /// Window Acknowledgement Size (§5.4.4).
    pub window_ack_size: u32,
    /// RTMP `app` name for the `connect` command.
    pub app: String,
    /// Publishing name (stream key) for the `publish` command, or the stream name `play` asks
    /// for in play mode.
    pub stream_key: String,
    /// `tcUrl` for the `connect` command (e.g. `rtmp://host/app`).
    pub tc_url: Option<String>,
    /// Ceiling on the total payload bytes this session's
    /// [`ChunkAssembler`] may buffer across **all** in-progress messages
    /// at once (#1108/RTMP-W1); see
    /// [`crate::chunk::DEFAULT_MAX_IN_PROGRESS_BYTES`] for the default.
    pub max_in_progress_bytes: usize,
}

/// Manual `Debug`: the stream key is a publish secret and never renders
/// (issue #1142).
impl core::fmt::Debug for RtmpClientConfig {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("RtmpClientConfig")
            .field("mode", &self.mode)
            .field("play_buffer", &self.play_buffer)
            .field("chunk_size", &self.chunk_size)
            .field("window_ack_size", &self.window_ack_size)
            .field("app", &self.app)
            .field("stream_key", &"<redacted>")
            .field("tc_url", &self.tc_url)
            .field("max_in_progress_bytes", &self.max_in_progress_bytes)
            .finish()
    }
}

impl Default for RtmpClientConfig {
    fn default() -> Self {
        Self {
            mode: ClientMode::Publish,
            play_buffer: DEFAULT_PLAY_BUFFER,
            chunk_size: 4096,
            window_ack_size: 2_500_000,
            app: String::new(),
            stream_key: String::new(),
            tc_url: None,
            max_in_progress_bytes: DEFAULT_MAX_IN_PROGRESS_BYTES,
        }
    }
}

/// Typed events [`ClientSession::handle_data`] surfaces.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum ClientEvent {
    /// Server accepted `connect`.
    Connected {
        /// Properties from `_result`.
        properties: Vec<(String, Amf0Value)>,
    },
    /// Server allocated a stream id.
    StreamCreated {
        /// The allocated message stream id.
        stream_id: u32,
    },
    /// Server accepted `publish` — session is now publishing.
    Publishing,
    /// Server accepted `play` (`NetStream.Play.Start`): media follows. Play mode only.
    Playing {
        /// The server announced the stream as recorded (User Control StreamIsRecorded, §6.7)
        /// before starting it, so its end is final; a live stream's end is not.
        recorded: bool,
    },
    /// One FLV chunk of played media: the payload of a single Audio(8)/Video(9)/Data-AMF0(18)
    /// message as an FLV tag (+ `PreviousTagSize`), the very first chunk prefixed with the FLV
    /// file header. Concatenating every chunk in order yields a valid FLV stream. Play mode only.
    Media {
        /// FLV bytes for this tag.
        flv: Vec<u8>,
    },
    /// The played stream ended: User Control Stream EOF (§6.7) or `NetStream.Play.Stop` /
    /// `NetStream.Play.Complete`. Play mode only.
    StreamEnded,
    /// Server returned an error.
    Error {
        /// Status code.
        code: String,
        /// Description.
        description: String,
    },
    /// Session closed.
    Closed,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum ClientState {
    Init,
    HandshakeDone,
    ConnectSent { txn_id: f64 },
    Connected,
    CreateStreamSent { txn_id: f64 },
    StreamCreated,
    PublishSent,
    Publishing,
    PlaySent,
    Playing,
}

/// Client-side handshake: generate C0+C1, consume S0+S1+S2, produce C2.
#[derive(Debug)]
struct ClientHandshake {
    state: ClientHandshakeState,
    local_time: u32,
    local_random: [u8; 1528],
}

#[derive(Debug)]
enum ClientHandshakeState {
    SendC0C1,
    WaitS0S1S2,
    Done,
}

impl ClientHandshake {
    fn new() -> Self {
        Self {
            state: ClientHandshakeState::SendC0C1,
            local_time: 0,
            local_random: default_random_fill(),
        }
    }

    fn start(&mut self) -> Vec<u8> {
        let c0 = Version(RTMP_VERSION);
        let c1 = HandshakePacket {
            time: self.local_time,
            zero: 0,
            random: self.local_random,
        };
        let mut out = vec![0u8; VERSION_LEN + HANDSHAKE_PACKET_LEN];
        out[..VERSION_LEN].copy_from_slice(&c0.to_bytes());
        out[VERSION_LEN..].copy_from_slice(&c1.to_bytes());
        self.state = ClientHandshakeState::WaitS0S1S2;
        out
    }

    fn read(&mut self, input: &[u8]) -> Result<(Vec<u8>, usize, bool)> {
        match &self.state {
            ClientHandshakeState::SendC0C1 => Ok((Vec::new(), 0, false)),
            ClientHandshakeState::WaitS0S1S2 => {
                let need = VERSION_LEN + HANDSHAKE_PACKET_LEN + HANDSHAKE_PACKET_LEN;
                need_in(input, need, "S0+S1+S2")?;
                let s0 = Version::parse(&input[..VERSION_LEN])?;
                // #1108/RTMP-W11: see handshake.rs's identical C0 check.
                if s0.0 != RTMP_VERSION {
                    return Err(RtmpError::HandshakeVersion {
                        value: s0.0,
                        expected: RTMP_VERSION,
                    });
                }
                let s1 = HandshakePacket::parse(
                    &input[VERSION_LEN..VERSION_LEN + HANDSHAKE_PACKET_LEN],
                )?;
                let _s2 = EchoPacket::parse(&input[VERSION_LEN + HANDSHAKE_PACKET_LEN..need])?;

                let c2 = EchoPacket {
                    time: s1.time,
                    time2: 0,
                    random_echo: s1.random,
                };
                let mut reply = vec![0u8; HANDSHAKE_PACKET_LEN];
                c2.serialize_into(&mut reply)?;

                self.state = ClientHandshakeState::Done;
                Ok((reply, need, true))
            }
            ClientHandshakeState::Done => Ok((Vec::new(), 0, true)),
        }
    }

    fn is_done(&self) -> bool {
        matches!(self.state, ClientHandshakeState::Done)
    }
}

/// Sans-IO RTMP client publish session.
#[derive(Debug)]
pub struct ClientSession {
    config: RtmpClientConfig,
    handshake: ClientHandshake,
    handshake_buf: Vec<u8>,
    assembler: ChunkAssembler,
    writer: ChunkWriter,
    state: ClientState,
    stream_id: Option<MessageStreamId>,
    next_txn_id: f64,
    ack_threshold: u32,
    bytes_received: u64,
    bytes_acked: u64,
    /// The peer's declared limit on OUR outbound bandwidth (§5.4.5's
    /// `SetPeerBandwidth`), tracked separately from `ack_threshold`
    /// (#1108/RTMP-W7): it constrains how much *we send*, not how often
    /// *we acknowledge received bytes* (that's `WindowAckSize`, §5.4.4).
    /// Not otherwise enforced by this sans-IO engine (it doesn't do its
    /// own outbound rate limiting), but kept and exposed rather than
    /// silently discarded or conflated with `ack_threshold`.
    peer_bandwidth: Option<u32>,
    /// The window size we last advertised to the peer via our own
    /// outbound `WindowAckSize` (distinct from `ack_threshold`, which
    /// tracks the PEER's advertised window for OUR acking of THEIR
    /// data — #1108/RTMP-W7).
    advertised_window_ack_size: u32,
    flv: FlvTagWriter,
    stream_is_recorded: bool,
}

impl ClientSession {
    /// Create a new client session.
    #[must_use]
    pub fn new(config: RtmpClientConfig) -> Self {
        let ack_threshold = config.window_ack_size;
        let advertised_window_ack_size = config.window_ack_size;
        let max_in_progress_bytes = config.max_in_progress_bytes;
        Self {
            config,
            handshake: ClientHandshake::new(),
            handshake_buf: Vec::new(),
            assembler: ChunkAssembler::new().with_max_in_progress_bytes(max_in_progress_bytes),
            writer: ChunkWriter::new(),
            state: ClientState::Init,
            stream_id: None,
            next_txn_id: 1.0,
            ack_threshold,
            bytes_received: 0,
            bytes_acked: 0,
            peer_bandwidth: None,
            advertised_window_ack_size,
            flv: FlvTagWriter::default(),
            stream_is_recorded: false,
        }
    }

    /// Produce C0+C1 handshake bytes. Call once at session start.
    pub fn start(&mut self) -> Vec<u8> {
        self.handshake.start()
    }

    /// Feed inbound bytes. Returns `(outbound bytes, events)`.
    pub fn handle_data(&mut self, input: &[u8]) -> Result<(Vec<u8>, Vec<ClientEvent>)> {
        let mut out = Vec::new();
        let mut events = Vec::new();

        let chunk_input = match self.drive_handshake(input, &mut out, &mut events)? {
            Some(bytes) => bytes,
            None => return Ok((out, events)),
        };

        self.bytes_received = self.bytes_received.saturating_add(chunk_input.len() as u64);

        self.assembler.feed(chunk_input);
        while let Some(msg) = self.assembler.next_message()? {
            self.dispatch_message(&msg, &mut out, &mut events)?;
        }

        self.maybe_ack(&mut out)?;
        Ok((out, events))
    }

    /// Encode an audio message (type 8). Only valid in `Publishing` state.
    ///
    /// `timestamp` is the media timestamp on the publisher's own clock
    /// (§5.1.3), carried on the wire as whole milliseconds.
    pub fn send_audio(&mut self, timestamp: Timestamp, data: &[u8]) -> Result<Vec<u8>> {
        if self.state != ClientState::Publishing {
            return Err(RtmpError::UnexpectedState {
                what: "send_audio requires the Publishing state",
            });
        }
        let msg = Message {
            chunk_stream_id: ChunkStreamId::new(4),
            timestamp,
            message_type_id: MessageTypeId::Audio,
            message_stream_id: self.stream_id.unwrap_or(MessageStreamId::new(1)),
            payload: data.to_vec(),
        };
        self.writer.write(&msg)
    }

    /// Encode a video message (type 9). Only valid in `Publishing` state.
    ///
    /// `timestamp` is the media timestamp on the publisher's own clock
    /// (§5.1.3), carried on the wire as whole milliseconds.
    pub fn send_video(&mut self, timestamp: Timestamp, data: &[u8]) -> Result<Vec<u8>> {
        if self.state != ClientState::Publishing {
            return Err(RtmpError::UnexpectedState {
                what: "send_video requires the Publishing state",
            });
        }
        let msg = Message {
            chunk_stream_id: ChunkStreamId::new(5),
            timestamp,
            message_type_id: MessageTypeId::Video,
            message_stream_id: self.stream_id.unwrap_or(MessageStreamId::new(1)),
            payload: data.to_vec(),
        };
        self.writer.write(&msg)
    }

    /// Encode a metadata message (`@setDataFrame`/`onMetaData`, type 18).
    pub fn send_metadata(&mut self, metadata: &[(String, Amf0Value)]) -> Result<Vec<u8>> {
        if self.state != ClientState::Publishing {
            return Err(RtmpError::UnexpectedState {
                what: "send_metadata requires the Publishing state",
            });
        }
        let mut payload = Amf0Value::String("@setDataFrame".to_string()).try_to_bytes()?;
        payload.extend(Amf0Value::String("onMetaData".to_string()).try_to_bytes()?);
        let obj = Amf0Value::Object(metadata.to_vec());
        payload.extend(obj.try_to_bytes()?);
        let msg = Message {
            chunk_stream_id: ChunkStreamId::new(4),
            timestamp: Timestamp::ZERO,
            message_type_id: MessageTypeId::DataAmf0,
            message_stream_id: self.stream_id.unwrap_or(MessageStreamId::new(1)),
            payload,
        };
        self.writer.write(&msg)
    }

    /// Whether the session has reached `Publishing` state.
    #[must_use]
    pub fn is_publishing(&self) -> bool {
        self.state == ClientState::Publishing
    }

    fn drive_handshake<'a>(
        &mut self,
        input: &'a [u8],
        out: &mut Vec<u8>,
        events: &mut Vec<ClientEvent>,
    ) -> Result<Option<&'a [u8]>> {
        if self.handshake.is_done() && self.state != ClientState::Init {
            return Ok(Some(input));
        }

        self.handshake_buf.extend_from_slice(input);

        if !self.handshake.is_done() {
            match self.handshake.read(&self.handshake_buf) {
                Ok((reply, consumed, done)) => {
                    out.extend_from_slice(&reply);
                    self.handshake_buf.drain(..consumed);
                    if done {
                        self.state = ClientState::HandshakeDone;
                        out.extend_from_slice(&self.build_connect()?);
                    }
                }
                Err(RtmpError::BufferTooShort(..)) => {
                    return Ok(None);
                }
                Err(e) => return Err(e),
            }
        }

        if self.handshake.is_done() && !self.handshake_buf.is_empty() {
            let remaining = core::mem::take(&mut self.handshake_buf);
            self.bytes_received = self.bytes_received.saturating_add(remaining.len() as u64);
            self.assembler.feed(&remaining);
            while let Some(msg) = self.assembler.next_message()? {
                self.dispatch_message(&msg, out, events)?;
            }
        }

        Ok(None)
    }

    fn build_connect(&mut self) -> Result<Vec<u8>> {
        let txn_id = self.next_txn_id;
        self.next_txn_id += 1.0;
        self.state = ClientState::ConnectSent { txn_id };

        let tc_url = self
            .config
            .tc_url
            .clone()
            .unwrap_or_else(|| format!("rtmp://localhost/{}", self.config.app));

        let cmd = Command {
            name: "connect".to_string(),
            transaction_id: txn_id,
            arguments: vec![Amf0Value::Object(vec![
                (
                    "app".to_string(),
                    Amf0Value::String(self.config.app.clone()),
                ),
                (
                    "flashVer".to_string(),
                    Amf0Value::String(FLASH_VER.to_string()),
                ),
                ("tcUrl".to_string(), Amf0Value::String(tc_url)),
                (
                    "type".to_string(),
                    Amf0Value::String("nonprivate".to_string()),
                ),
            ])],
        };

        let mut out = Vec::new();

        let chunk_size = ChunkSize::try_new(self.config.chunk_size)?;
        let set_chunk_size = ProtocolControl::SetChunkSize(chunk_size);
        out.extend_from_slice(&self.writer.write(&set_chunk_size.to_message())?);
        self.writer.set_chunk_size(chunk_size);

        let window_ack = ProtocolControl::WindowAckSize(self.config.window_ack_size);
        out.extend_from_slice(&self.writer.write(&window_ack.to_message())?);

        let msg = Message {
            chunk_stream_id: ChunkStreamId::new(COMMAND_CHUNK_STREAM_ID),
            timestamp: Timestamp::ZERO,
            message_type_id: MessageTypeId::CommandAmf0,
            message_stream_id: MessageStreamId::new(0),
            payload: cmd.to_body()?,
        };
        out.extend_from_slice(&self.writer.write(&msg)?);
        Ok(out)
    }

    /// `releaseStream` + `FCPublish` (each `(null, stream_key)`, fire-and-
    /// forget: their `_result`s carry transaction ids the state machine
    /// never waits on) then `createStream` — the ffmpeg/OBS/FMLE sequence
    /// some CDN ingest front ends require (#1108/RTMP-W9).
    fn build_publish_preamble_and_create_stream(&mut self) -> Result<Vec<u8>> {
        let mut out = Vec::new();
        for name in [CMD_RELEASE_STREAM, CMD_FC_PUBLISH] {
            let txn_id = self.next_txn_id;
            self.next_txn_id += 1.0;
            let cmd = Command {
                name: name.to_string(),
                transaction_id: txn_id,
                arguments: vec![
                    Amf0Value::Null,
                    Amf0Value::String(self.config.stream_key.clone()),
                ],
            };
            let msg = Message {
                chunk_stream_id: ChunkStreamId::new(COMMAND_CHUNK_STREAM_ID),
                timestamp: Timestamp::ZERO,
                message_type_id: MessageTypeId::CommandAmf0,
                message_stream_id: MessageStreamId::new(0),
                payload: cmd.to_body()?,
            };
            out.extend_from_slice(&self.writer.write(&msg)?);
        }
        out.extend_from_slice(&self.build_create_stream()?);
        Ok(out)
    }

    fn build_create_stream(&mut self) -> Result<Vec<u8>> {
        let txn_id = self.next_txn_id;
        self.next_txn_id += 1.0;
        self.state = ClientState::CreateStreamSent { txn_id };

        let cmd = Command {
            name: "createStream".to_string(),
            transaction_id: txn_id,
            arguments: vec![Amf0Value::Null],
        };
        let msg = Message {
            chunk_stream_id: ChunkStreamId::new(COMMAND_CHUNK_STREAM_ID),
            timestamp: Timestamp::ZERO,
            message_type_id: MessageTypeId::CommandAmf0,
            message_stream_id: MessageStreamId::new(0),
            payload: cmd.to_body()?,
        };
        self.writer.write(&msg)
    }

    fn build_publish(&mut self) -> Result<Vec<u8>> {
        self.state = ClientState::PublishSent;

        let cmd = Command {
            name: "publish".to_string(),
            transaction_id: 0.0,
            arguments: vec![
                Amf0Value::Null,
                Amf0Value::String(self.config.stream_key.clone()),
                Amf0Value::String("live".to_string()),
            ],
        };
        let msg = Message {
            chunk_stream_id: ChunkStreamId::new(COMMAND_CHUNK_STREAM_ID),
            timestamp: Timestamp::ZERO,
            message_type_id: MessageTypeId::CommandAmf0,
            message_stream_id: self.stream_id.unwrap_or(MessageStreamId::new(1)),
            payload: cmd.to_body()?,
        };
        self.writer.write(&msg)
    }

    /// `SetBufferLength` (§6.7) then `play` (§7.2.2.1) on the created stream.
    fn build_play(&mut self) -> Result<Vec<u8>> {
        self.state = ClientState::PlaySent;
        let stream_id = self.stream_id.unwrap_or(MessageStreamId::new(1));
        let mut out = Vec::new();
        let buffer = UserControl::SetBufferLength {
            stream_id: stream_id.get(),
            buffer: self.config.play_buffer,
        };
        out.extend_from_slice(&self.writer.write(&buffer.to_message()?)?);
        let cmd = Command {
            name: "play".to_string(),
            transaction_id: 0.0,
            arguments: vec![
                Amf0Value::Null,
                Amf0Value::String(self.config.stream_key.clone()),
                Amf0Value::Number(PLAY_START_LIVE_OR_RECORDED),
            ],
        };
        let msg = Message {
            chunk_stream_id: ChunkStreamId::new(COMMAND_CHUNK_STREAM_ID),
            timestamp: Timestamp::ZERO,
            message_type_id: MessageTypeId::CommandAmf0,
            message_stream_id: stream_id,
            payload: cmd.to_body()?,
        };
        out.extend_from_slice(&self.writer.write(&msg)?);
        Ok(out)
    }

    fn receiving_media(&self) -> bool {
        matches!(self.state, ClientState::PlaySent | ClientState::Playing)
    }

    fn emit_media(
        &mut self,
        tag_type: MessageTypeId,
        timestamp: u32,
        payload: &[u8],
        events: &mut Vec<ClientEvent>,
    ) -> Result<()> {
        let flv = self.flv.tag(tag_type, timestamp, payload)?;
        events.push(ClientEvent::Media { flv });
        Ok(())
    }

    fn dispatch_message(
        &mut self,
        msg: &Message,
        out: &mut Vec<u8>,
        events: &mut Vec<ClientEvent>,
    ) -> Result<()> {
        if let Some(pc) = ProtocolControl::from_message(msg)? {
            match pc {
                ProtocolControl::SetChunkSize(size) => {
                    self.assembler.set_chunk_size(size);
                }
                ProtocolControl::WindowAckSize(size) => {
                    self.ack_threshold = size;
                }
                ProtocolControl::SetPeerBandwidth {
                    ack_window_size, ..
                } => {
                    // #1108/RTMP-W7: §5.4.5 limits the RECEIVER's (i.e.
                    // our) *output* bandwidth — it says nothing about how
                    // often we acknowledge inbound bytes, which is
                    // `WindowAckSize`'s job (§5.4.4) and already handled by
                    // the arm above. This used to overwrite `ack_threshold`
                    // with the peer's bandwidth-limit value, and echo that
                    // same value back as if it were our own advertised
                    // window. Track it separately; reply with our OWN
                    // configured window size, and only when it actually
                    // changed from what we last advertised (private/specs-verified/rtmp/rtmp-runtime/rtmp.md
                    // §5.4.5: "Receiver SHOULD reply with Window Ack Size
                    // if its window differs from the last one it
                    // advertised").
                    self.peer_bandwidth = Some(ack_window_size);
                    if self.advertised_window_ack_size != self.config.window_ack_size {
                        self.advertised_window_ack_size = self.config.window_ack_size;
                        let ack = ProtocolControl::WindowAckSize(self.advertised_window_ack_size);
                        out.extend_from_slice(&self.writer.write(&ack.to_message())?);
                    }
                }
                // #1108/RTMP-W2: was ignored — see `ChunkAssembler::abort`'s doc.
                ProtocolControl::Abort { chunk_stream_id } => {
                    self.assembler.abort(ChunkStreamId::new(chunk_stream_id));
                }
                _ => {}
            }
            return Ok(());
        }
        if msg.message_type_id == MessageTypeId::CommandAmf0 {
            let cmd = Command::parse(&msg.payload)?;
            self.handle_command(&cmd, out, events)?;
        }
        if msg.message_type_id == MessageTypeId::CommandAmf3 {
            let body = msg
                .payload
                .get(1..)
                .ok_or(RtmpError::BufferTooShort(BufferTooShort {
                    need: 1,
                    have: msg.payload.len(),
                    what: "AMF3 command encoding marker byte",
                }))?;
            let cmd = Command::parse(body)?;
            self.handle_command(&cmd, out, events)?;
        }
        if self.receiving_media() {
            match msg.message_type_id {
                MessageTypeId::Audio | MessageTypeId::Video | MessageTypeId::DataAmf0 => {
                    self.emit_media(
                        msg.message_type_id,
                        msg.timestamp.millis(),
                        &msg.payload,
                        events,
                    )?;
                }
                MessageTypeId::Aggregate => {
                    unpack_aggregate(msg, |tag_type, timestamp, payload| {
                        self.emit_media(tag_type, timestamp, payload, events)
                    })?;
                }
                _ => {}
            }
        }
        if msg.message_type_id == MessageTypeId::UserControl {
            // #1108/RTMP-W8: servers that probe liveness with User Control
            // PingRequest (event 6 — FMS/Wowza) got no PingResponse and may
            // have dropped the publisher; malformed/unrecognised event
            // types are tolerated, same as the server side's inbound
            // handling.
            match UserControl::parse(&msg.payload) {
                Ok(UserControl::PingRequest(ts)) => {
                    let reply = UserControl::PingResponse(ts);
                    out.extend_from_slice(&self.writer.write(&reply.to_message()?)?);
                }
                Ok(UserControl::StreamIsRecorded(_)) if self.receiving_media() => {
                    self.stream_is_recorded = true;
                }
                Ok(UserControl::StreamEof(_)) if self.receiving_media() => {
                    events.push(ClientEvent::StreamEnded);
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn handle_command(
        &mut self,
        cmd: &Command,
        out: &mut Vec<u8>,
        events: &mut Vec<ClientEvent>,
    ) -> Result<()> {
        match cmd.name.as_str() {
            "_result" => self.handle_result(cmd, out, events),
            "_error" => {
                let (code, desc) = extract_status(&cmd.arguments);
                events.push(ClientEvent::Error {
                    code,
                    description: desc,
                });
                Ok(())
            }
            "onStatus" => self.handle_on_status(cmd, events),
            _ => Ok(()),
        }
    }

    fn handle_result(
        &mut self,
        cmd: &Command,
        out: &mut Vec<u8>,
        events: &mut Vec<ClientEvent>,
    ) -> Result<()> {
        match self.state {
            ClientState::ConnectSent { txn_id } if (cmd.transaction_id - txn_id).abs() < 0.5 => {
                let props = match cmd.arguments.first() {
                    Some(Amf0Value::Object(pairs)) => pairs.clone(),
                    _ => Vec::new(),
                };
                events.push(ClientEvent::Connected { properties: props });
                self.state = ClientState::Connected;
                match self.config.mode {
                    ClientMode::Play => out.extend_from_slice(&self.build_create_stream()?),
                    _ => out.extend_from_slice(&self.build_publish_preamble_and_create_stream()?),
                }
            }
            ClientState::CreateStreamSent { txn_id }
                if (cmd.transaction_id - txn_id).abs() < 0.5 =>
            {
                let sid = MessageStreamId::new(match cmd.arguments.last() {
                    Some(Amf0Value::Number(n)) => *n as u32,
                    _ => 1,
                });
                self.stream_id = Some(sid);
                events.push(ClientEvent::StreamCreated {
                    stream_id: sid.get(),
                });
                self.state = ClientState::StreamCreated;
                match self.config.mode {
                    ClientMode::Play => out.extend_from_slice(&self.build_play()?),
                    _ => out.extend_from_slice(&self.build_publish()?),
                }
            }
            _ => {}
        }
        Ok(())
    }

    fn handle_on_status(&mut self, cmd: &Command, events: &mut Vec<ClientEvent>) -> Result<()> {
        let (code, desc) = extract_status(&cmd.arguments);
        if self.config.mode == ClientMode::Play {
            let is_error = extract_status_level(&cmd.arguments) == STATUS_LEVEL_ERROR
                || code == STATUS_PLAY_STREAM_NOT_FOUND
                || code == STATUS_PLAY_FAILED;
            if is_error {
                events.push(ClientEvent::Error {
                    code,
                    description: desc,
                });
            } else if code == STATUS_PLAY_START {
                self.state = ClientState::Playing;
                events.push(ClientEvent::Playing {
                    recorded: self.stream_is_recorded,
                });
            } else if code == STATUS_PLAY_STOP || code == STATUS_PLAY_COMPLETE {
                events.push(ClientEvent::StreamEnded);
            }
            return Ok(());
        }
        if code == "NetStream.Publish.Start" {
            self.state = ClientState::Publishing;
            events.push(ClientEvent::Publishing);
        } else {
            events.push(ClientEvent::Error {
                code,
                description: desc,
            });
        }
        Ok(())
    }

    fn maybe_ack(&mut self, out: &mut Vec<u8>) -> Result<()> {
        if self.ack_threshold == 0 {
            return Ok(());
        }
        if self.bytes_received.wrapping_sub(self.bytes_acked) >= u64::from(self.ack_threshold) {
            let seq = SequenceNumber::new((self.bytes_received & 0xFFFF_FFFF) as u32);
            let ack = ProtocolControl::Acknowledgement(seq);
            out.extend_from_slice(&self.writer.write(&ack.to_message())?);
            self.bytes_acked = self.bytes_received;
        }
        Ok(())
    }
}

fn extract_status_level(args: &[Amf0Value]) -> String {
    args.iter()
        .find_map(|arg| match arg {
            Amf0Value::Object(pairs) => pairs.iter().find_map(|(k, v)| match (k.as_str(), v) {
                ("level", Amf0Value::String(s)) => Some(s.clone()),
                _ => None,
            }),
            _ => None,
        })
        .unwrap_or_default()
}

fn extract_status(args: &[Amf0Value]) -> (String, String) {
    for arg in args {
        if let Amf0Value::Object(pairs) = arg {
            let code = pairs
                .iter()
                .find(|(k, _)| k == "code")
                .and_then(|(_, v)| match v {
                    Amf0Value::String(s) => Some(s.clone()),
                    _ => None,
                })
                .unwrap_or_default();
            let desc = pairs
                .iter()
                .find(|(k, _)| k == "description")
                .and_then(|(_, v)| match v {
                    Amf0Value::String(s) => Some(s.clone()),
                    _ => None,
                })
                .unwrap_or_default();
            if !code.is_empty() {
                return (code, desc);
            }
        }
    }
    (String::new(), String::new())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::handshake;
    use crate::server::{RtmpServerConfig, ServerSession};

    #[test]
    fn client_handshake_round_trip() {
        let mut client_hs = ClientHandshake::new();
        let mut server_hs = handshake::Handshake::new();

        let c0_c1 = client_hs.start();
        assert!(!client_hs.is_done());

        let (s0_s1_s2, consumed, _done) = server_hs.read(&c0_c1).unwrap();
        assert_eq!(consumed, c0_c1.len());

        let (c2, consumed2, done2) = client_hs.read(&s0_s1_s2).unwrap();
        assert_eq!(consumed2, s0_s1_s2.len());
        assert!(done2);
        assert!(client_hs.is_done());
        assert_eq!(c2.len(), HANDSHAKE_PACKET_LEN);

        let (_reply, consumed3, done3) = server_hs.read(&c2).unwrap();
        assert_eq!(consumed3, HANDSHAKE_PACKET_LEN);
        assert!(done3);
    }

    /// RTMP-W11 (#1108): S0's version byte used to be parsed and discarded.
    #[test]
    fn client_handshake_rejects_bad_s0_version() {
        let mut client_hs = ClientHandshake::new();
        let mut server_hs = handshake::Handshake::new();
        let c0_c1 = client_hs.start();
        let (mut s0_s1_s2, _consumed, _done) = server_hs.read(&c0_c1).unwrap();
        s0_s1_s2[0] = 6; // RTMPE, not plain RTMP
        let err = client_hs.read(&s0_s1_s2).unwrap_err();
        assert!(matches!(
            err,
            RtmpError::HandshakeVersion {
                value: 6,
                expected: RTMP_VERSION
            }
        ));
    }

    /// RTMP-W9 (#1108): after `connect`'s `_result` the client must send
    /// `releaseStream` -> `FCPublish` -> `createStream` (ffmpeg/OBS/FMLE
    /// order), and `connect` must carry `flashVer`. Fails without the fix
    /// (the client sent a bare `createStream`).
    #[test]
    fn client_publish_sequence_mirrors_ffmpeg() {
        let config = RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test_key".to_string(),
            ..RtmpClientConfig::default()
        };
        let mut client = ClientSession::new(config);
        let mut server = ServerSession::new(
            RtmpServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
        );
        let c0_c1 = client.start();
        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
        let (mut to_server, _) = client.handle_data(&s0_s1_s2).unwrap();
        let mut names = Vec::new();
        let mut connect_has_flash_ver = false;
        let mut sniff = ChunkAssembler::new();
        for round in 0..4 {
            // Round 0's output starts with C2, which is not chunk data.
            let skip = if round == 0 { HANDSHAKE_PACKET_LEN } else { 0 };
            sniff.set_chunk_size(
                crate::message::ChunkSize::new(client.config.chunk_size)
                    .expect("the client's own configured size is validated before connect"),
            );
            for m in sniff.push(&to_server[skip..]).unwrap() {
                if m.message_type_id == MessageTypeId::CommandAmf0 {
                    let c = Command::parse(&m.payload).unwrap();
                    if c.name == "connect" {
                        connect_has_flash_ver = matches!(
                            c.arguments.first(),
                            Some(Amf0Value::Object(p)) if p.iter().any(|(k, _)| k == "flashVer")
                        );
                    }
                    names.push(c.name);
                }
            }
            let (to_client, _) = server.handle_data(&to_server).unwrap();
            let (next, _) = client.handle_data(&to_client).unwrap();
            to_server = next;
        }
        assert!(connect_has_flash_ver);
        assert_eq!(
            names,
            [
                "connect",
                "releaseStream",
                "FCPublish",
                "createStream",
                "publish"
            ]
        );
        assert!(client.is_publishing());
    }

    /// RTMP-W8 (#1108): the client never answered a User Control
    /// PingRequest (event 6 — FMS/Wowza liveness probe), so a server that
    /// probes with it got no PingResponse and may drop the publisher.
    #[test]
    fn client_replies_to_ping_request_with_ping_response() {
        let config = RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test_key".to_string(),
            ..RtmpClientConfig::default()
        };
        let mut client = ClientSession::new(config);
        let c0_c1 = client.start();
        let mut server = ServerSession::new(
            RtmpServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
        );
        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
        let (_client_out, _) = client.handle_data(&s0_s1_s2).unwrap();

        let ping = UserControl::PingRequest(0xDEAD_BEEF);
        let bytes = ChunkWriter::new()
            .write(&ping.to_message().unwrap())
            .unwrap();

        let (out, _events) = client.handle_data(&bytes).unwrap();
        let mut assembler = ChunkAssembler::new();
        let messages = assembler.push(&out).unwrap();
        let reply = messages
            .iter()
            .find(|m| m.message_type_id == MessageTypeId::UserControl)
            .map(|m| UserControl::parse(&m.payload).unwrap());
        assert_eq!(reply, Some(UserControl::PingResponse(0xDEAD_BEEF)));
    }

    /// RTMP-W7 (#1108): `SetPeerBandwidth` used to overwrite `ack_threshold`
    /// with the peer's declared OUTBOUND bandwidth limit — a value with no
    /// relation to how often we should acknowledge inbound bytes
    /// (`WindowAckSize`'s job, §5.4.4). It's now tracked separately in
    /// `peer_bandwidth`, and `ack_threshold` is untouched.
    #[test]
    fn set_peer_bandwidth_does_not_corrupt_ack_threshold() {
        let config = RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test_key".to_string(),
            ..RtmpClientConfig::default()
        };
        let original_ack_threshold_config = config.window_ack_size;
        let mut client = ClientSession::new(config.clone());
        assert_eq!(client.ack_threshold, original_ack_threshold_config);

        // Complete the handshake so `handle_data` dispatches chunk messages
        // (rather than still buffering handshake bytes).
        let c0_c1 = client.start();
        let mut server = ServerSession::new(
            RtmpServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
        );
        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
        client.handle_data(&s0_s1_s2).unwrap();

        let spb = crate::message::ProtocolControl::SetPeerBandwidth {
            ack_window_size: 999_999,
            limit_type: crate::message::LimitType::Hard,
        };
        let bytes = ChunkWriter::new().write(&spb.to_message()).unwrap();
        let (_out, _events) = client.handle_data(&bytes).unwrap();

        assert_eq!(
            client.ack_threshold, original_ack_threshold_config,
            "ack_threshold must not be overwritten by SetPeerBandwidth"
        );
        assert_eq!(client.peer_bandwidth, Some(999_999));
    }

    /// The invalid-chunk-size rejection on the wire: a client configured
    /// with a size §5.4.1 forbids fails its `connect` with the typed
    /// `RtmpError::Malformed`, before any `SetChunkSize` message is built,
    /// and emits nothing. The former `try_to_message` fold-panic is
    /// unreachable now that `ChunkSize` validates at construction.
    #[test]
    fn client_connect_with_invalid_chunk_size_errors_before_any_message() {
        let config = RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test_key".to_string(),
            chunk_size: 0x8000_0000,
            ..RtmpClientConfig::default()
        };
        let mut client = ClientSession::new(config);
        let mut server = ServerSession::new(RtmpServerConfig::default());
        let c0_c1 = client.start();
        let (s0_s1_s2, _) = server.handle_data(&c0_c1).unwrap();
        let err = client.handle_data(&s0_s1_s2).unwrap_err();
        assert!(
            matches!(err, RtmpError::ChunkSizeOutOfRange { value: 0x8000_0000 }),
            "{err:?}"
        );
        assert!(!client.is_publishing());
    }

    #[test]
    fn client_connect_flow() {
        let config = RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test_key".to_string(),
            ..RtmpClientConfig::default()
        };
        let mut client = ClientSession::new(config);
        let c0_c1 = client.start();

        let mut server = ServerSession::new(
            RtmpServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
        );

        let (s0_s1_s2, server_events) = server.handle_data(&c0_c1).unwrap();
        assert!(server_events.is_empty());

        let (client_out, _client_events) = client.handle_data(&s0_s1_s2).unwrap();
        assert!(
            !client_out.is_empty(),
            "client should emit C2 + connect + protocol control"
        );

        let (server_reply, server_events) = server.handle_data(&client_out).unwrap();
        assert!(
            server_events
                .iter()
                .any(|e| matches!(e, crate::server::ServerEvent::Connected { .. })),
            "server should see connect: {server_events:?}"
        );

        let (client_out2, client_events2) = client.handle_data(&server_reply).unwrap();
        assert!(
            client_events2
                .iter()
                .any(|e| matches!(e, ClientEvent::Connected { .. })),
            "client should see Connected: {client_events2:?}"
        );
        // `client_out2` alone is not a reliable auto-advance signal: the
        // server's connect reply also carries a `SetPeerBandwidth` protocol
        // control message, which the client acks unconditionally — so bytes
        // come back even if `createStream` itself never fires. Check the
        // actual state transition instead (issue #933 finding M2).
        let _ = client_out2;
        assert!(
            matches!(client.state, ClientState::CreateStreamSent { .. }),
            "client should auto-advance from Connected to CreateStreamSent: {:?}",
            client.state
        );
    }

    /// Drives the full client auto-advance —
    /// `connect` -> `createStream` -> `publish` — end to end against a real
    /// [`ServerSession`], and asserts every state transition actually
    /// happens (issue #933 finding M2: the prior version of this test
    /// buried its post-`Connected` assertions inside
    /// `if !client_out2.is_empty() { .. }` guards, so a broken auto-advance
    /// that emitted no bytes would make the test vacuously pass instead of
    /// fail).
    #[test]
    fn client_full_publish_flow() {
        let config = RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test_key".to_string(),
            ..RtmpClientConfig::default()
        };
        let mut client = ClientSession::new(config);
        let c0_c1 = client.start();

        let mut server = ServerSession::new(
            RtmpServerConfig::default().with_expected_stream_key(Some("test_key".to_string())),
        );

        // Handshake.
        let (s0_s1_s2, server_events) = server.handle_data(&c0_c1).unwrap();
        assert!(server_events.is_empty());

        // Client completes the handshake and sends C2 + connect.
        let (client_out, client_events) = client.handle_data(&s0_s1_s2).unwrap();
        assert!(
            !client_out.is_empty(),
            "client should emit C2 + connect + protocol control"
        );
        assert!(
            client_events.is_empty(),
            "no client events expected before the server replies: {client_events:?}"
        );
        assert_eq!(client.state, ClientState::ConnectSent { txn_id: 1.0 });

        // Server completes the handshake and accepts connect.
        let (server_reply, server_events) = server.handle_data(&client_out).unwrap();
        assert!(
            server_events
                .iter()
                .any(|e| matches!(e, crate::server::ServerEvent::Connected { .. })),
            "server should see connect: {server_events:?}"
        );

        // Client sees Connected and auto-advances: emits createStream.
        let (client_out2, client_events2) = client.handle_data(&server_reply).unwrap();
        assert!(
            client_events2
                .iter()
                .any(|e| matches!(e, ClientEvent::Connected { .. })),
            "client should see Connected: {client_events2:?}"
        );
        assert!(
            !client_out2.is_empty(),
            "client should auto-advance from Connected and emit createStream"
        );
        assert!(matches!(client.state, ClientState::CreateStreamSent { .. }));

        // Server replies to createStream with an allocated stream id.
        let (server_reply2, _server_events2) = server.handle_data(&client_out2).unwrap();
        assert!(
            !server_reply2.is_empty(),
            "server should reply to createStream"
        );

        // Client sees StreamCreated and auto-advances: emits publish.
        let (client_out3, client_events3) = client.handle_data(&server_reply2).unwrap();
        assert!(
            client_events3
                .iter()
                .any(|e| matches!(e, ClientEvent::StreamCreated { .. })),
            "client should see StreamCreated: {client_events3:?}"
        );
        assert!(
            !client_out3.is_empty(),
            "client should auto-advance from StreamCreated and emit publish"
        );
        assert_eq!(client.state, ClientState::PublishSent);

        // Server accepts publish.
        let (server_reply3, server_events3) = server.handle_data(&client_out3).unwrap();
        assert!(
            server_events3
                .iter()
                .any(|e| matches!(e, crate::server::ServerEvent::Publish { .. })),
            "server should see publish: {server_events3:?}"
        );
        assert!(
            !server_reply3.is_empty(),
            "server should reply onStatus for publish"
        );

        // Client sees Publishing — the auto-advance has run to completion.
        let (_client_out4, client_events4) = client.handle_data(&server_reply3).unwrap();
        assert!(
            client_events4
                .iter()
                .any(|e| matches!(e, ClientEvent::Publishing)),
            "client should see Publishing: {client_events4:?}"
        );
        assert_eq!(client.state, ClientState::Publishing);
        assert!(client.is_publishing());
    }

    #[test]
    fn send_audio_video_while_publishing() {
        let config = RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test".to_string(),
            ..RtmpClientConfig::default()
        };
        let mut client = ClientSession::new(config);
        client.state = ClientState::Publishing;
        client.stream_id = Some(MessageStreamId::new(1));

        let audio = client
            .send_audio(Timestamp::from_millis(100), &[0xAA, 0xBB])
            .unwrap();
        assert!(!audio.is_empty());

        let video = client
            .send_video(Timestamp::from_millis(200), &[0xCC, 0xDD, 0xEE])
            .unwrap();
        assert!(!video.is_empty());

        let meta = client
            .send_metadata(&[
                ("width".to_string(), Amf0Value::Number(1920.0)),
                ("height".to_string(), Amf0Value::Number(1080.0)),
            ])
            .unwrap();
        assert!(!meta.is_empty());
    }

    /// T15: an Amf0 String over the u16 length cap inside the metadata
    /// object must surface as `Err`, not a `to_bytes` panic.
    #[test]
    fn send_metadata_over_range_string_errors_not_panics() {
        let mut client = ClientSession::new(RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test".to_string(),
            ..RtmpClientConfig::default()
        });
        client.state = ClientState::Publishing;
        client.stream_id = Some(MessageStreamId::new(1));
        let huge = "x".repeat(usize::from(u16::MAX) + 1);
        let r = client.send_metadata(&[("title".to_string(), Amf0Value::String(huge))]);
        assert!(
            matches!(r, Err(RtmpError::Amf0StringTooLong { .. })),
            "{r:?}"
        );
    }

    #[test]
    fn send_audio_before_publishing_fails() {
        let config = RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test".to_string(),
            ..RtmpClientConfig::default()
        };
        let mut client = ClientSession::new(config);
        assert!(matches!(
            client.send_audio(Timestamp::from_millis(0), &[0x00]),
            Err(crate::error::RtmpError::UnexpectedState { .. })
        ));
    }

    #[test]
    fn connect_error_produces_event() {
        let config = RtmpClientConfig {
            app: "live".to_string(),
            stream_key: "test".to_string(),
            ..RtmpClientConfig::default()
        };
        let mut client = ClientSession::new(config);
        client.handshake.state = ClientHandshakeState::Done;
        client.state = ClientState::ConnectSent { txn_id: 1.0 };

        let error_cmd = Command {
            name: "_error".to_string(),
            transaction_id: 1.0,
            arguments: vec![
                Amf0Value::Null,
                Amf0Value::Object(vec![
                    (
                        "code".to_string(),
                        Amf0Value::String("NetConnection.Connect.Rejected".to_string()),
                    ),
                    (
                        "description".to_string(),
                        Amf0Value::String("Connection refused".to_string()),
                    ),
                ]),
            ],
        };
        let msg = Message {
            chunk_stream_id: ChunkStreamId::new(COMMAND_CHUNK_STREAM_ID),
            timestamp: Timestamp::ZERO,
            message_type_id: MessageTypeId::CommandAmf0,
            message_stream_id: MessageStreamId::new(0),
            payload: error_cmd.to_body().unwrap(),
        };
        let bytes = ChunkWriter::new().write(&msg).unwrap();

        let (_, events) = client.handle_data(&bytes).unwrap();
        assert!(
            events.iter().any(|e| matches!(
                e,
                ClientEvent::Error { code, .. } if code == "NetConnection.Connect.Rejected"
            )),
            "expected Error event: {events:?}"
        );
    }
}