|
| 1 | +use anyhow::Result; |
| 2 | +use retina::client::{SessionGroup, SetupOptions}; |
| 3 | +use retina::codec::CodecItem; |
| 4 | +use sandpolis_instance::network::StreamResponder; |
| 5 | +use sandpolis_macros::Stream; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | +use std::sync::Arc; |
| 8 | +use tokio::sync::RwLock; |
| 9 | +use tokio::sync::mpsc::Sender; |
| 10 | +use tracing::debug; |
| 11 | +use url::Url; |
| 12 | + |
| 13 | +#[derive(Serialize, Deserialize, Debug, Clone)] |
| 14 | +pub struct RtspConfig { |
| 15 | + pub port: u16, |
| 16 | + pub username: String, |
| 17 | + pub password: String, |
| 18 | + pub path: String, |
| 19 | +} |
| 20 | + |
| 21 | +/// Request message for RTSP stream sessions. |
| 22 | +#[derive(Serialize, Deserialize)] |
| 23 | +pub enum RtspSessionStreamRequest { |
| 24 | + /// Start streaming from the given RTSP URL |
| 25 | + Start { |
| 26 | + /// Full RTSP URL (e.g., rtsp://user:pass@host:554/stream) |
| 27 | + url: String, |
| 28 | + |
| 29 | + /// Transport protocol preference |
| 30 | + transport: RtspTransport, |
| 31 | + }, |
| 32 | + /// Stop the stream |
| 33 | + Stop, |
| 34 | +} |
| 35 | + |
| 36 | +/// Transport protocol for RTSP streaming. |
| 37 | +#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default)] |
| 38 | +pub enum RtspTransport { |
| 39 | + /// UDP transport (lower latency, may have packet loss) |
| 40 | + Udp, |
| 41 | + /// TCP interleaved transport (more reliable) |
| 42 | + #[default] |
| 43 | + Tcp, |
| 44 | +} |
| 45 | + |
| 46 | +/// Response message containing video/audio frame data. |
| 47 | +#[derive(Serialize, Deserialize)] |
| 48 | +pub struct RtspSessionStreamResponse { |
| 49 | + /// The stream index (0 for video, 1 for audio typically) |
| 50 | + pub stream_index: usize, |
| 51 | + |
| 52 | + /// Frame data |
| 53 | + pub frame: RtspFrame, |
| 54 | +} |
| 55 | + |
| 56 | +/// A single frame from the RTSP stream. |
| 57 | +#[derive(Serialize, Deserialize)] |
| 58 | +pub enum RtspFrame { |
| 59 | + /// H.264 video frame |
| 60 | + H264 { |
| 61 | + /// NAL units |
| 62 | + data: Vec<Vec<u8>>, |
| 63 | + /// Presentation timestamp in 90kHz units |
| 64 | + timestamp: i64, |
| 65 | + /// Whether this is a keyframe (IDR) |
| 66 | + is_keyframe: bool, |
| 67 | + }, |
| 68 | + /// H.265/HEVC video frame |
| 69 | + H265 { |
| 70 | + /// NAL units |
| 71 | + data: Vec<Vec<u8>>, |
| 72 | + /// Presentation timestamp in 90kHz units |
| 73 | + timestamp: i64, |
| 74 | + /// Whether this is a keyframe |
| 75 | + is_keyframe: bool, |
| 76 | + }, |
| 77 | + /// AAC audio frame |
| 78 | + Aac { |
| 79 | + /// Raw AAC data |
| 80 | + data: Vec<u8>, |
| 81 | + /// Presentation timestamp |
| 82 | + timestamp: i64, |
| 83 | + }, |
| 84 | + /// G.711 audio frame |
| 85 | + G711 { |
| 86 | + /// Raw audio samples |
| 87 | + data: Vec<u8>, |
| 88 | + /// Presentation timestamp |
| 89 | + timestamp: i64, |
| 90 | + }, |
| 91 | + /// Stream ended or error occurred |
| 92 | + End { reason: String }, |
| 93 | +} |
| 94 | + |
| 95 | +/// Stream responder that connects to an RTSP source and forwards frames. |
| 96 | +#[cfg(any(feature = "agent", feature = "server"))] |
| 97 | +#[derive(Stream, Default)] |
| 98 | +pub struct RtspSessionStreamResponder { |
| 99 | + /// Flag to signal the stream should stop |
| 100 | + stop_flag: Arc<RwLock<bool>>, |
| 101 | +} |
| 102 | + |
| 103 | +#[cfg(any(feature = "agent", feature = "server"))] |
| 104 | +impl StreamResponder for RtspSessionStreamResponder { |
| 105 | + type In = RtspSessionStreamRequest; |
| 106 | + type Out = RtspSessionStreamResponse; |
| 107 | + |
| 108 | + async fn on_message(&self, request: Self::In, sender: Sender<Self::Out>) -> Result<()> { |
| 109 | + match request { |
| 110 | + RtspSessionStreamRequest::Start { url, transport } => { |
| 111 | + // Reset stop flag |
| 112 | + *self.stop_flag.write().await = false; |
| 113 | + |
| 114 | + // Parse the URL |
| 115 | + let parsed_url = Url::parse(&url)?; |
| 116 | + debug!( |
| 117 | + "Connecting to RTSP stream: {}", |
| 118 | + parsed_url.host_str().unwrap_or("unknown") |
| 119 | + ); |
| 120 | + |
| 121 | + // Create session options based on transport preference |
| 122 | + let session_group = Arc::new(SessionGroup::default()); |
| 123 | + let mut session = retina::client::Session::describe( |
| 124 | + parsed_url, |
| 125 | + retina::client::SessionOptions::default().session_group(session_group), |
| 126 | + ) |
| 127 | + .await?; |
| 128 | + |
| 129 | + // Setup all streams |
| 130 | + for i in 0..session.streams().len() { |
| 131 | + let setup_options = match transport { |
| 132 | + RtspTransport::Udp => SetupOptions::default() |
| 133 | + .transport(retina::client::Transport::Udp(Default::default())), |
| 134 | + RtspTransport::Tcp => SetupOptions::default() |
| 135 | + .transport(retina::client::Transport::Tcp(Default::default())), |
| 136 | + }; |
| 137 | + session.setup(i, setup_options).await?; |
| 138 | + } |
| 139 | + |
| 140 | + // Start playing |
| 141 | + let mut session = session |
| 142 | + .play(retina::client::PlayOptions::default()) |
| 143 | + .await? |
| 144 | + .demuxed()?; |
| 145 | + |
| 146 | + let stop_flag = self.stop_flag.clone(); |
| 147 | + |
| 148 | + // Read frames in a loop |
| 149 | + loop { |
| 150 | + // Check stop flag |
| 151 | + if *stop_flag.read().await { |
| 152 | + let _ = sender |
| 153 | + .send(RtspSessionStreamResponse { |
| 154 | + stream_index: 0, |
| 155 | + frame: RtspFrame::End { |
| 156 | + reason: "Stopped by request".to_string(), |
| 157 | + }, |
| 158 | + }) |
| 159 | + .await; |
| 160 | + break; |
| 161 | + } |
| 162 | + |
| 163 | + use futures::StreamExt; |
| 164 | + match session.next().await { |
| 165 | + Some(Ok(item)) => { |
| 166 | + let response = match item { |
| 167 | + CodecItem::VideoFrame(frame) => { |
| 168 | + let stream_id = frame.stream_id(); |
| 169 | + let is_keyframe = frame.is_random_access_point(); |
| 170 | + let timestamp = frame.timestamp().timestamp(); |
| 171 | + let data = frame.into_data(); |
| 172 | + |
| 173 | + RtspSessionStreamResponse { |
| 174 | + stream_index: stream_id, |
| 175 | + frame: RtspFrame::H264 { |
| 176 | + data: vec![data], |
| 177 | + timestamp, |
| 178 | + is_keyframe, |
| 179 | + }, |
| 180 | + } |
| 181 | + } |
| 182 | + CodecItem::AudioFrame(frame) => { |
| 183 | + let timestamp = frame.timestamp().timestamp(); |
| 184 | + let data = frame.data().to_vec(); |
| 185 | + |
| 186 | + RtspSessionStreamResponse { |
| 187 | + stream_index: frame.stream_id(), |
| 188 | + frame: RtspFrame::Aac { data, timestamp }, |
| 189 | + } |
| 190 | + } |
| 191 | + CodecItem::MessageFrame(_) => continue, |
| 192 | + _ => continue, |
| 193 | + }; |
| 194 | + |
| 195 | + if sender.send(response).await.is_err() { |
| 196 | + break; |
| 197 | + } |
| 198 | + } |
| 199 | + Some(Err(e)) => { |
| 200 | + let _ = sender |
| 201 | + .send(RtspSessionStreamResponse { |
| 202 | + stream_index: 0, |
| 203 | + frame: RtspFrame::End { |
| 204 | + reason: e.to_string(), |
| 205 | + }, |
| 206 | + }) |
| 207 | + .await; |
| 208 | + break; |
| 209 | + } |
| 210 | + None => { |
| 211 | + let _ = sender |
| 212 | + .send(RtspSessionStreamResponse { |
| 213 | + stream_index: 0, |
| 214 | + frame: RtspFrame::End { |
| 215 | + reason: "Stream ended".to_string(), |
| 216 | + }, |
| 217 | + }) |
| 218 | + .await; |
| 219 | + break; |
| 220 | + } |
| 221 | + } |
| 222 | + } |
| 223 | + } |
| 224 | + RtspSessionStreamRequest::Stop => { |
| 225 | + *self.stop_flag.write().await = true; |
| 226 | + } |
| 227 | + } |
| 228 | + Ok(()) |
| 229 | + } |
| 230 | +} |
| 231 | + |
| 232 | +#[cfg(any(feature = "agent", feature = "server"))] |
| 233 | +impl Drop for RtspSessionStreamResponder { |
| 234 | + fn drop(&mut self) { |
| 235 | + debug!("RTSP session responder dropped"); |
| 236 | + // Signal stop in case the stream is still running |
| 237 | + if let Ok(mut flag) = self.stop_flag.try_write() { |
| 238 | + *flag = true; |
| 239 | + } |
| 240 | + } |
| 241 | +} |
0 commit comments