From 1beaea8088ed20b9bd87afa6c1d0adf84b9350bb Mon Sep 17 00:00:00 2001 From: dailz Date: Sat, 6 Jun 2026 21:16:55 +0800 Subject: [PATCH] fix(webrtc): use MediaAdded event to discover video mid instead of hardcoded iteration (closes #11) --- src/webrtc.rs | 47 ++++++++++++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/src/webrtc.rs b/src/webrtc.rs index 7c7aa8f..a099c2e 100644 --- a/src/webrtc.rs +++ b/src/webrtc.rs @@ -311,28 +311,26 @@ impl WebRtcInner { } fn discover_video_params(&mut self) { - for s in ["0", "1", "2", "3"] { - let mid: Mid = s.into(); - if let Some(media) = self.rtc.media(mid) { - if media.kind() == MediaKind::Video { - tracing::info!("Found video media: mid={mid}"); - self.video_mid = Some(mid); + let mid = match self.video_mid { + Some(m) => m, + None => { + tracing::warn!("discover_video_params: no video_mid yet"); + return; + } + }; + self.video_pt = None; + if let Some(writer) = self.rtc.writer(mid) { + for pp in writer.payload_params() { + tracing::debug!("Codec: pt={:?} spec={:?}", pp.pt(), pp.spec()); + if pp.spec().codec.is_video() && pp.spec().codec == Codec::H264 { + self.video_pt = Some(pp.pt()); + tracing::info!("H.264 payload type: {:?}", pp.pt()); break; } } } - - if let Some(mid) = self.video_mid { - if let Some(writer) = self.rtc.writer(mid) { - for pp in writer.payload_params() { - tracing::debug!("Codec: pt={:?} spec={:?}", pp.pt(), pp.spec()); - if pp.spec().codec.is_video() && pp.spec().codec == Codec::H264 { - self.video_pt = Some(pp.pt()); - tracing::info!("H.264 payload type: {:?}", pp.pt()); - break; - } - } - } + if self.video_pt.is_none() { + tracing::warn!("discover_video_params: no H.264 codec found for mid={mid}"); } } @@ -360,7 +358,18 @@ impl WebRtcInner { return Ok(true); } Event::MediaAdded(ma) => { - tracing::info!("Media added: mid={:?}", ma.mid); + tracing::info!("Media added: mid={} kind={:?}", ma.mid, ma.kind); + if ma.kind == MediaKind::Video { + if let Some(media) = self.rtc.media(ma.mid) { + if media.direction().is_sending() + && self.video_mid.is_none() + { + self.video_mid = Some(ma.mid); + tracing::info!("Captured video mid: {}", ma.mid); + self.discover_video_params(); + } + } + } } _ => { tracing::debug!("WebRTC event: {:?}", e);