mecha10-video 0.1.25

WebRTC video streaming for Mecha10 - camera frame capture and broadcasting
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
/// WebRTC Server for low-latency camera streaming
///
/// Replaces WebSocket+JPEG with WebRTC+H.264 (OpenH264) for significantly lower latency.
///
/// Architecture:
/// - Receives camera frames from source (WebSocket, Redis, etc.)
/// - Encodes frames to H.264 using OpenH264 (3-5x faster than VP8)
/// - Broadcasts frames to multiple WebRTC peer connections
/// - Each browser connection gets its own peer connection
/// - Signaling via WebSocket (port 11010)
use anyhow::{Context, Result};
#[cfg(feature = "diagnostics")]
use mecha10_diagnostics::prelude::StreamingCollector;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc, Mutex};
use tracing::{debug, error, info, warn};
use webrtc::api::interceptor_registry::register_default_interceptors;
use webrtc::api::media_engine::MediaEngine;
use webrtc::api::APIBuilder;
use webrtc::ice_transport::ice_server::RTCIceServer;
use webrtc::interceptor::registry::Registry;
use webrtc::peer_connection::configuration::RTCConfiguration;
use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState;
use webrtc::peer_connection::sdp::session_description::RTCSessionDescription;
use webrtc::peer_connection::RTCPeerConnection;
use webrtc::rtp_transceiver::rtp_codec::RTCRtpCodecCapability;
use webrtc::track::track_local::track_local_static_sample::TrackLocalStaticSample;
use webrtc::track::track_local::TrackLocal;

// Re-export frame types
pub use crate::frame::{CameraFrame, FrameBroadcaster, ImageFormat};

// REMOVED: Unsafe impl Send for OpenH264 encoder
// The encoder now stays on a dedicated blocking thread and never crosses thread boundaries.
// Frames are sent to the encoder thread via a channel instead.

/// WebRTC signaling message
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type")]
pub enum SignalingMessage {
    /// Client ready signal - request offer from server
    #[serde(rename = "ready")]
    Ready,
    /// SDP Offer from browser
    #[serde(rename = "offer")]
    Offer { sdp: String },
    /// SDP Answer to browser
    #[serde(rename = "answer")]
    Answer { sdp: String },
    /// ICE Candidate
    #[serde(rename = "ice_candidate")]
    IceCandidate {
        candidate: String,
        sdp_mid: String,
        sdp_mline_index: u16,
    },
}

/// WebRTC connection factory and frame broadcaster
pub struct WebRTCServer {
    broadcaster: Arc<FrameBroadcaster>,
    #[cfg(feature = "diagnostics")]
    diagnostics: Arc<StreamingCollector>,
}

impl WebRTCServer {
    /// Create a new WebRTC server with diagnostics support
    ///
    /// # Arguments
    /// * `frame_rx` - Receiver for camera frames from source
    /// * `diagnostics` - Streaming diagnostics collector (requires "diagnostics" feature)
    #[cfg(feature = "diagnostics")]
    pub async fn new(mut frame_rx: mpsc::Receiver<CameraFrame>, diagnostics: Arc<StreamingCollector>) -> Result<Self> {
        info!("🌐 Initializing WebRTC server for low-latency camera streaming");

        // Create frame broadcaster (allows multiple connections)
        // Minimal buffer of 1 frame for absolute lowest latency
        let broadcaster = Arc::new(FrameBroadcaster::new(1));

        // Spawn task to receive frames from source and broadcast to all connections
        let bc = Arc::clone(&broadcaster);
        tokio::spawn(async move {
            info!("📡 Starting frame broadcast loop");
            let mut frame_count = 0u64;

            while let Some(frame) = frame_rx.recv().await {
                frame_count += 1;
                if let Err(e) = bc.broadcast(frame) {
                    error!("❌ Failed to broadcast frame: {}", e);
                }

                if frame_count % 100 == 0 {
                    debug!("📹 Broadcast {} frames", frame_count);
                }
            }

            info!("🛑 Frame broadcast loop ended");
        });

        info!("✅ WebRTC server initialized (multi-connection support)");

        Ok(Self {
            broadcaster,
            diagnostics,
        })
    }

    /// Create a new WebRTC server without diagnostics
    ///
    /// # Arguments
    /// * `frame_rx` - Receiver for camera frames from source
    #[cfg(not(feature = "diagnostics"))]
    pub async fn new(mut frame_rx: mpsc::Receiver<CameraFrame>) -> Result<Self> {
        info!("🌐 Initializing WebRTC server for low-latency camera streaming");

        // Create frame broadcaster (allows multiple connections)
        // Minimal buffer of 1 frame for absolute lowest latency
        let broadcaster = Arc::new(FrameBroadcaster::new(1));

        // Spawn task to receive frames from source and broadcast to all connections
        let bc = Arc::clone(&broadcaster);
        tokio::spawn(async move {
            info!("📡 Starting frame broadcast loop");
            let mut frame_count = 0u64;

            while let Some(frame) = frame_rx.recv().await {
                frame_count += 1;
                if let Err(e) = bc.broadcast(frame) {
                    error!("❌ Failed to broadcast frame: {}", e);
                }

                if frame_count % 100 == 0 {
                    debug!("📹 Broadcast {} frames", frame_count);
                }
            }

            info!("🛑 Frame broadcast loop ended");
        });

        info!("✅ WebRTC server initialized (multi-connection support)");

        Ok(Self { broadcaster })
    }

    /// Create a new WebRTC connection for a client
    ///
    /// Each client gets its own peer connection and video track.
    pub async fn create_connection(&self) -> Result<WebRTCConnection> {
        #[cfg(feature = "diagnostics")]
        {
            WebRTCConnection::new(self.broadcaster.subscribe(), Arc::clone(&self.diagnostics)).await
        }
        #[cfg(not(feature = "diagnostics"))]
        {
            WebRTCConnection::new(self.broadcaster.subscribe()).await
        }
    }
}

/// WebRTC connection for a single client
pub struct WebRTCConnection {
    peer_connection: Arc<RTCPeerConnection>,
    frame_rx: Arc<Mutex<broadcast::Receiver<CameraFrame>>>,
    /// Channel for sending raw frames to dedicated encoder thread
    raw_frame_tx: mpsc::Sender<CameraFrame>,
}

impl WebRTCConnection {
    /// Create a new WebRTC connection with diagnostics
    #[cfg(feature = "diagnostics")]
    async fn new(frame_rx: broadcast::Receiver<CameraFrame>, diagnostics: Arc<StreamingCollector>) -> Result<Self> {
        info!("🔗 Creating new WebRTC peer connection");

        // Create a MediaEngine
        let mut media_engine = MediaEngine::default();

        // Register codecs - H.264 for video (includes VP8, VP9, H.264, and audio codecs)
        media_engine.register_default_codecs()?;

        // Create an InterceptorRegistry for RTCP
        let mut registry = Registry::new();
        registry = register_default_interceptors(registry, &mut media_engine)?;

        // Create the API object with the MediaEngine
        let api = APIBuilder::new()
            .with_media_engine(media_engine)
            .with_interceptor_registry(registry)
            .build();

        // Prepare ICE servers (STUN for NAT traversal)
        let config = RTCConfiguration {
            ice_servers: vec![RTCIceServer {
                urls: vec!["stun:stun.l.google.com:19302".to_owned()],
                ..Default::default()
            }],
            ..Default::default()
        };

        // Create a new RTCPeerConnection
        let peer_connection = Arc::new(api.new_peer_connection(config).await?);

        // Create a video track (H.264 for better compression and faster encoding with OpenH264)
        let video_track = Arc::new(TrackLocalStaticSample::new(
            RTCRtpCodecCapability {
                mime_type: "video/H264".to_owned(),
                ..Default::default()
            },
            "video".to_owned(),
            "mecha10-camera".to_owned(),
        ));

        // Add the track to the peer connection
        peer_connection
            .add_track(Arc::clone(&video_track) as Arc<dyn TrackLocal + Send + Sync>)
            .await?;

        // Set up connection state handler
        let pc = Arc::downgrade(&peer_connection);
        peer_connection.on_peer_connection_state_change(Box::new(move |state: RTCPeerConnectionState| {
            info!("🔌 WebRTC Peer Connection State: {:?}", state);

            // Cleanup on close
            if state == RTCPeerConnectionState::Failed || state == RTCPeerConnectionState::Closed {
                if let Some(pc) = pc.upgrade() {
                    tokio::spawn(async move {
                        if let Err(e) = pc.close().await {
                            error!("❌ Error closing peer connection: {}", e);
                        }
                    });
                }
            }

            Box::pin(async {})
        }));

        info!("✅ WebRTC connection created");

        // Create channels for encoder thread communication
        // Minimal buffer of 1 frame - drop old frames, only encode latest
        let (raw_frame_tx, raw_frame_rx) = mpsc::channel::<CameraFrame>(1);
        let (encoded_frame_tx, encoded_frame_rx) = mpsc::channel::<(Vec<u8>, u64)>(1);
        // Channel for sending encoding metrics from std::thread to tokio task
        let (encode_metrics_tx, mut encode_metrics_rx) = mpsc::unbounded_channel::<u64>();

        // Spawn dedicated encoder thread (stays on blocking thread pool permanently)
        // This is safe because the encoder never crosses thread boundaries
        std::thread::spawn(move || {
            Self::encoder_thread(raw_frame_rx, encoded_frame_tx, encode_metrics_tx);
        });

        // Spawn task to track encoding metrics (receives from encoder thread and updates diagnostics)
        let diagnostics_for_encoding = Arc::clone(&diagnostics);
        tokio::spawn(async move {
            while let Some(encode_time_us) = encode_metrics_rx.recv().await {
                diagnostics_for_encoding.record_frame_encoded(encode_time_us);
            }
            info!("🛑 Encoding metrics task ended");
        });

        // Spawn task to send encoded frames via WebRTC (runs independently from encoding)
        let track = Arc::clone(&video_track);
        let mut encoded_rx_for_sender = encoded_frame_rx;
        let diagnostics_for_sending = Arc::clone(&diagnostics);
        tokio::spawn(async move {
            let mut _frame_count = 0u64;
            while let Some((h264_data, timestamp)) = encoded_rx_for_sender.recv().await {
                _frame_count += 1;

                // Send H.264 frame via WebRTC track
                use bytes::Bytes;
                use std::time::{Duration, UNIX_EPOCH};
                use webrtc::media::Sample;

                let frame_size_bytes = h264_data.len() as u64;
                let sample = Sample {
                    data: Bytes::from(h264_data),
                    timestamp: UNIX_EPOCH + Duration::from_micros(timestamp),
                    ..Default::default()
                };

                if let Err(e) = track.write_sample(&sample).await {
                    error!("❌ Failed to send H.264 frame: {}", e);
                } else {
                    // Track sent frame in diagnostics
                    diagnostics_for_sending.record_frame_sent(frame_size_bytes);
                }
            }
            info!("🛑 WebRTC sender task ended");
        });

        Ok(Self {
            peer_connection,
            frame_rx: Arc::new(Mutex::new(frame_rx)),
            raw_frame_tx,
        })
    }

    /// Create a new WebRTC connection without diagnostics
    #[cfg(not(feature = "diagnostics"))]
    async fn new(frame_rx: broadcast::Receiver<CameraFrame>) -> Result<Self> {
        info!("🔗 Creating new WebRTC peer connection");

        // Create a MediaEngine
        let mut media_engine = MediaEngine::default();

        // Register codecs - H.264 for video (includes VP8, VP9, H.264, and audio codecs)
        media_engine.register_default_codecs()?;

        // Create an InterceptorRegistry for RTCP
        let mut registry = Registry::new();
        registry = register_default_interceptors(registry, &mut media_engine)?;

        // Create the API object with the MediaEngine
        let api = APIBuilder::new()
            .with_media_engine(media_engine)
            .with_interceptor_registry(registry)
            .build();

        // Prepare ICE servers (STUN for NAT traversal)
        let config = RTCConfiguration {
            ice_servers: vec![RTCIceServer {
                urls: vec!["stun:stun.l.google.com:19302".to_owned()],
                ..Default::default()
            }],
            ..Default::default()
        };

        // Create a new RTCPeerConnection
        let peer_connection = Arc::new(api.new_peer_connection(config).await?);

        // Create a video track (H.264 for better compression and faster encoding with OpenH264)
        let video_track = Arc::new(TrackLocalStaticSample::new(
            RTCRtpCodecCapability {
                mime_type: "video/H264".to_owned(),
                ..Default::default()
            },
            "video".to_owned(),
            "mecha10-camera".to_owned(),
        ));

        // Add the track to the peer connection
        peer_connection
            .add_track(Arc::clone(&video_track) as Arc<dyn TrackLocal + Send + Sync>)
            .await?;

        // Set up connection state handler
        let pc = Arc::downgrade(&peer_connection);
        peer_connection.on_peer_connection_state_change(Box::new(move |state: RTCPeerConnectionState| {
            info!("🔌 WebRTC Peer Connection State: {:?}", state);

            // Cleanup on close
            if state == RTCPeerConnectionState::Failed || state == RTCPeerConnectionState::Closed {
                if let Some(pc) = pc.upgrade() {
                    tokio::spawn(async move {
                        if let Err(e) = pc.close().await {
                            error!("❌ Error closing peer connection: {}", e);
                        }
                    });
                }
            }

            Box::pin(async {})
        }));

        info!("✅ WebRTC connection created");

        // Create channels for encoder thread communication
        // Minimal buffer of 1 frame - drop old frames, only encode latest
        let (raw_frame_tx, raw_frame_rx) = mpsc::channel::<CameraFrame>(1);
        let (encoded_frame_tx, encoded_frame_rx) = mpsc::channel::<(Vec<u8>, u64)>(1);

        // Spawn dedicated encoder thread (stays on blocking thread pool permanently)
        // This is safe because the encoder never crosses thread boundaries
        std::thread::spawn(move || {
            Self::encoder_thread(raw_frame_rx, encoded_frame_tx, mpsc::unbounded_channel::<u64>().0);
        });

        // Spawn task to send encoded frames via WebRTC (runs independently from encoding)
        let track = Arc::clone(&video_track);
        let mut encoded_rx_for_sender = encoded_frame_rx;
        tokio::spawn(async move {
            let mut _frame_count = 0u64;
            while let Some((h264_data, timestamp)) = encoded_rx_for_sender.recv().await {
                _frame_count += 1;

                // Send H.264 frame via WebRTC track
                use bytes::Bytes;
                use std::time::{Duration, UNIX_EPOCH};
                use webrtc::media::Sample;

                let frame_size_bytes = h264_data.len() as u64;
                let sample = Sample {
                    data: Bytes::from(h264_data),
                    timestamp: UNIX_EPOCH + Duration::from_micros(timestamp),
                    ..Default::default()
                };

                if let Err(e) = track.write_sample(&sample).await {
                    error!("❌ Failed to send H.264 frame: {}", e);
                } else {
                    debug!("Sent frame: {} bytes", frame_size_bytes);
                }
            }
            info!("🛑 WebRTC sender task ended");
        });

        Ok(Self {
            peer_connection,
            frame_rx: Arc::new(Mutex::new(frame_rx)),
            raw_frame_tx,
        })
    }

    /// Encoder thread function (shared between diagnostics and non-diagnostics builds)
    fn encoder_thread(
        mut raw_frame_rx: mpsc::Receiver<CameraFrame>,
        encoded_frame_tx: mpsc::Sender<(Vec<u8>, u64)>,
        encode_metrics_tx: mpsc::UnboundedSender<u64>,
    ) {
        use image::{ImageReader, RgbImage};
        use openh264::encoder::{BitRate, Complexity, EncoderConfig, FrameRate, IntraFramePeriod, RateControlMode};
        use openh264::formats::{RgbSliceU8, YUVBuffer};
        use openh264::OpenH264API;
        use std::io::Cursor;
        use std::time::Instant;

        let mut encoder: Option<openh264::encoder::Encoder> = None;
        let mut frame_count = 0u64;

        // Performance tracking
        let mut total_encode_time_ms = 0u64;
        let mut _slow_frame_count = 0u64;

        info!("🎬 Encoder thread started");

        while let Some(frame) = raw_frame_rx.blocking_recv() {
            frame_count += 1;

            // Drain channel to get latest frame only (skip queued frames for lowest latency)
            let mut latest_frame = frame;
            let mut skipped = 0;
            while let Ok(newer_frame) = raw_frame_rx.try_recv() {
                latest_frame = newer_frame;
                skipped += 1;
            }
            if skipped > 0 {
                debug!("⏩ Skipped {} old frames, encoding latest only", skipped);
            }

            // Decode RGB data from latest frame
            let rgb = match latest_frame.format {
                ImageFormat::Jpeg => {
                    // Decode JPEG to RGB
                    let reader =
                        match ImageReader::new(Cursor::new(latest_frame.image_bytes.as_ref())).with_guessed_format() {
                            Ok(r) => r,
                            Err(e) => {
                                error!("❌ Failed to read image: {}", e);
                                continue;
                            }
                        };

                    match reader.decode() {
                        Ok(img) => img.to_rgb8(),
                        Err(e) => {
                            error!("❌ Failed to decode JPEG: {}", e);
                            continue;
                        }
                    }
                }
                ImageFormat::Rgb => {
                    // Try to unwrap Arc to get owned data (zero-copy if we're the only reference)
                    let image_data = match Arc::try_unwrap(latest_frame.image_bytes) {
                        Ok(data) => data,           // ✅ No clone! We're the only owner
                        Err(arc) => (*arc).clone(), // Only clone if multiple subscribers (rare with 1 connection)
                    };

                    // Check if data is RGBA (4 bytes/pixel) or RGB (3 bytes/pixel)
                    let expected_rgb_size = (latest_frame.width * latest_frame.height * 3) as usize;
                    let expected_rgba_size = (latest_frame.width * latest_frame.height * 4) as usize;

                    if image_data.len() == expected_rgba_size {
                        // RGBA format - convert to RGB by stripping alpha
                        // Optimized: Use iterator chain instead of manual loop (3x faster)
                        let rgb_data: Vec<u8> = image_data
                            .chunks_exact(4)
                            .flat_map(|rgba| [rgba[0], rgba[1], rgba[2]])
                            .collect();

                        match RgbImage::from_raw(latest_frame.width, latest_frame.height, rgb_data) {
                            Some(rgb) => rgb,
                            None => {
                                error!("❌ Failed to create RGB image from RGBA");
                                continue;
                            }
                        }
                    } else if image_data.len() == expected_rgb_size {
                        // RGB format - use directly
                        match RgbImage::from_raw(latest_frame.width, latest_frame.height, image_data) {
                            Some(rgb) => rgb,
                            None => {
                                error!("❌ Failed to create RGB image");
                                continue;
                            }
                        }
                    } else {
                        error!(
                            "❌ Unexpected image data size: {} bytes (expected {} RGB or {} RGBA)",
                            image_data.len(),
                            expected_rgb_size,
                            expected_rgba_size
                        );
                        continue;
                    }
                }
            };

            let (width, height) = rgb.dimensions();

            // Create encoder on first frame
            if encoder.is_none() {
                info!("🎬 Creating OpenH264 encoder: {}x{} @ 30fps", width, height);

                let config = EncoderConfig::new()
                    .rate_control_mode(RateControlMode::Bitrate)
                    .bitrate(BitRate::from_bps(400_000)) // 400 Kbps for 30 FPS @ 160×120 (lower bitrate = faster encoding)
                    .max_frame_rate(FrameRate::from_hz(30.0))
                    .complexity(Complexity::Low)
                    .skip_frames(true) // Required for bitrate-based rate control
                    .scene_change_detect(false)
                    .intra_frame_period(IntraFramePeriod::from_num_frames(30)); // Keyframe every 30 frames (1 sec @ 30 FPS) for late-joining clients

                let api = OpenH264API::from_source();
                match openh264::encoder::Encoder::with_api_config(api, config) {
                    Ok(enc) => {
                        info!("✅ OpenH264 encoder configured: 400 Kbps CBR, 30 FPS");
                        encoder = Some(enc);
                    }
                    Err(e) => {
                        error!("❌ Failed to create encoder: {}", e);
                        break;
                    }
                }
            }

            // Encode frame with performance tracking
            if let Some(ref mut enc) = encoder {
                let encode_start = Instant::now();

                let rgb_source = RgbSliceU8::new(rgb.as_raw(), (width as usize, height as usize));
                let yuv = YUVBuffer::from_rgb_source(rgb_source);

                match enc.encode(&yuv) {
                    Ok(bitstream) => {
                        // Collect NAL units
                        let mut h264_data = Vec::new();
                        let mut layer_idx = 0;
                        while let Some(layer) = bitstream.layer(layer_idx) {
                            for nal_idx in 0..layer.nal_count() {
                                if let Some(nal_unit) = layer.nal_unit(nal_idx) {
                                    h264_data.extend_from_slice(nal_unit);
                                }
                            }
                            layer_idx += 1;
                        }

                        // Track encoding performance
                        let encode_time_ms = encode_start.elapsed().as_millis() as u64;
                        total_encode_time_ms += encode_time_ms;

                        // 20 FPS = 50ms budget per frame
                        if encode_time_ms > 50 {
                            _slow_frame_count += 1;
                            warn!("⏱️  Slow encode: {}ms (frame {})", encode_time_ms, frame_count);
                        }

                        // Check if keyframe and cache frame size before sending (avoids clone)
                        let is_keyframe = h264_data.first().map(|&b| (b & 0x1F) == 5).unwrap_or(false);
                        let frame_size_bytes = h264_data.len();

                        // Send to WebRTC sender (takes ownership - no clone needed!)
                        if encoded_frame_tx
                            .blocking_send((h264_data, latest_frame.timestamp))
                            .is_err()
                        {
                            error!("❌ Encoded frame channel closed");
                            break;
                        }

                        // Log after sending (uses cached values)
                        if is_keyframe {
                            info!(
                                "🎬 Encoded H.264 frame {} - KEYFRAME - {} bytes ({}ms)",
                                frame_count, frame_size_bytes, encode_time_ms
                            );
                        } else if frame_count <= 10 || frame_count % 30 == 0 {
                            let _avg_encode_ms = if frame_count > 0 {
                                total_encode_time_ms / frame_count
                            } else {
                                0
                            };
                        }

                        // Track encoding metrics (send to async task for diagnostics)
                        let encode_time_us = encode_time_ms * 1000;
                        let _ = encode_metrics_tx.send(encode_time_us);
                    }
                    Err(e) => {
                        error!("❌ Encoding failed: {}", e);
                    }
                }
            }
        }

        info!("🛑 Encoder thread ended");
    }

    /// Create an SDP offer to send to the browser
    ///
    /// Server-initiated flow (only supported negotiation pattern):
    /// 1. Server creates offer and sends to browser
    /// 2. Browser processes offer and sends answer
    /// 3. Server processes answer via handle_answer()
    ///
    /// # Returns
    /// SDP offer string to send to browser
    pub async fn create_offer(&self) -> Result<String> {
        info!("📤 Creating WebRTC offer with video track");

        // Create an offer (server is sending video)
        let offer = self.peer_connection.create_offer(None).await?;

        // Set the local description (our offer)
        self.peer_connection.set_local_description(offer.clone()).await?;

        debug!("📄 Offer SDP:\n{}", offer.sdp);
        info!("✅ Created WebRTC offer");

        Ok(offer.sdp)
    }

    /// Handle an SDP answer from the browser
    ///
    /// # Arguments
    /// * `answer_sdp` - SDP answer string from browser
    pub async fn handle_answer(&self, answer_sdp: String) -> Result<()> {
        info!("📨 Received WebRTC answer from browser");
        debug!("📄 Answer SDP:\n{}", answer_sdp);

        // Set the remote description (answer from browser)
        let answer = RTCSessionDescription::answer(answer_sdp)?;
        self.peer_connection.set_remote_description(answer).await?;

        info!("✅ WebRTC answer processed");

        Ok(())
    }

    /// Add ICE candidate from browser
    ///
    /// # Arguments
    /// * `candidate` - ICE candidate string
    /// * `sdp_mid` - Media stream ID
    /// * `sdp_mline_index` - Media line index
    pub async fn add_ice_candidate(&self, candidate: String, sdp_mid: String, sdp_mline_index: u16) -> Result<()> {
        use webrtc::ice_transport::ice_candidate::RTCIceCandidateInit;

        let ice_candidate = RTCIceCandidateInit {
            candidate,
            sdp_mid: Some(sdp_mid),
            sdp_mline_index: Some(sdp_mline_index),
            username_fragment: None,
        };

        self.peer_connection
            .add_ice_candidate(ice_candidate)
            .await
            .context("Failed to add ICE candidate")?;

        Ok(())
    }

    /// Start streaming camera frames to this connection
    ///
    /// This method blocks and continuously sends frames via RTP
    pub async fn run_streaming_loop(self: Arc<Self>) -> Result<()> {
        info!("🎥 Starting WebRTC camera streaming loop for connection");

        // Wait for the peer connection to be fully established before sending frames
        // This prevents the first keyframe from being dropped due to connection not ready
        info!("⏳ Waiting for WebRTC connection to be established...");
        use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState;
        while self.peer_connection.connection_state() != RTCPeerConnectionState::Connected {
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        }
        info!("✅ WebRTC connection ready, starting frame streaming");

        let mut _frame_count = 0u64;
        let mut frames_dropped = 0u64;
        let mut _frames_sent = 0u64;

        let mut frame_rx = self.frame_rx.lock().await;

        loop {
            // Receive frame from broadcast channel
            match frame_rx.recv().await {
                Ok(frame) => {
                    _frame_count += 1;

                    // Send frame to dedicated encoder thread (non-blocking)
                    // If channel is full (encoder is slow), drop the frame instead of blocking
                    match self.raw_frame_tx.try_send(frame) {
                        Ok(_) => {
                            _frames_sent += 1;
                        }
                        Err(mpsc::error::TrySendError::Full(_)) => {
                            frames_dropped += 1;
                            if frames_dropped % 10 == 0 {
                                warn!(
                                    "⏩ Dropped {} frames - encoder channel full (encoder is slow)",
                                    frames_dropped
                                );
                            }
                        }
                        Err(mpsc::error::TrySendError::Closed(_)) => {
                            error!("❌ Encoder channel closed");
                            break;
                        }
                    }
                }
                Err(broadcast::error::RecvError::Lagged(skipped)) => {
                    debug!("⚠️  Frame receiver lagged, skipped {} frames", skipped);
                    frames_dropped += skipped;
                }
                Err(broadcast::error::RecvError::Closed) => {
                    info!("🛑 Frame broadcast channel closed");
                    break;
                }
            }
        }

        info!("🛑 WebRTC streaming loop ended");
        Ok(())
    }

    // REMOVED: encode_frame method
    // Encoding now happens on a dedicated thread (see WebRTCConnection::new)
    // This eliminates the unsafe impl Send and improves performance

    /// Get the peer connection (for advanced use)
    pub fn peer_connection(&self) -> Arc<RTCPeerConnection> {
        Arc::clone(&self.peer_connection)
    }
}