|
5 | 5 | """ |
6 | 6 |
|
7 | 7 | import asyncio |
| 8 | +import threading |
| 9 | +import time |
8 | 10 | from abc import ABC, abstractmethod |
9 | 11 | from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple |
10 | 12 |
|
11 | 13 | import cv2 |
12 | 14 | import numpy as np |
13 | 15 | from aiortc import RTCPeerConnection, VideoStreamTrack |
| 16 | +from aiortc.contrib.media import MediaPlayer |
| 17 | +from aiortc.mediastreams import VIDEO_CLOCK_RATE, VIDEO_PTIME, VIDEO_TIME_BASE |
14 | 18 | from av import VideoFrame |
15 | 19 |
|
16 | 20 | from inference_sdk.http.errors import InvalidParameterError |
@@ -181,6 +185,137 @@ async def cleanup(self) -> None: |
181 | 185 | self._track.release() |
182 | 186 |
|
183 | 187 |
|
| 188 | +class _PacedTrack(VideoStreamTrack): |
| 189 | + """Wraps a source track and paces frame delivery like VideoStreamTrack. |
| 190 | +
|
| 191 | + MediaPlayer's PlayerStreamTrack does NOT pace RTSP frames (RTSP is in |
| 192 | + REAL_TIME_FORMATS so _throttle_playback is False). This means frames |
| 193 | + are pulled from FFmpeg and forwarded to the RTP sender as fast as |
| 194 | + possible, causing packet bursts that overflow the receiver's jitter |
| 195 | + buffer. |
| 196 | +
|
| 197 | + This wrapper adds the same ~33 ms sleep between frames that the base |
| 198 | + VideoStreamTrack uses, preventing bursts. |
| 199 | + """ |
| 200 | + |
| 201 | + def __init__(self, source): # noqa: ANN001 |
| 202 | + super().__init__() |
| 203 | + self._source = source |
| 204 | + self._start_time: float = 0.0 |
| 205 | + self._pts = 0 |
| 206 | + |
| 207 | + async def recv(self) -> VideoFrame: |
| 208 | + from aiortc.mediastreams import MediaStreamError |
| 209 | + |
| 210 | + if self.readyState != "live": |
| 211 | + raise MediaStreamError |
| 212 | + |
| 213 | + frame = await self._source.recv() |
| 214 | + |
| 215 | + # Pace delivery: sleep until the next frame slot (~33 ms apart) |
| 216 | + if self._pts == 0: |
| 217 | + self._start_time = time.time() |
| 218 | + else: |
| 219 | + wait = self._start_time + (self._pts / VIDEO_CLOCK_RATE) - time.time() |
| 220 | + if wait > 0: |
| 221 | + await asyncio.sleep(wait) |
| 222 | + |
| 223 | + frame.pts = self._pts |
| 224 | + frame.time_base = VIDEO_TIME_BASE |
| 225 | + self._pts += int(VIDEO_PTIME * VIDEO_CLOCK_RATE) |
| 226 | + return frame |
| 227 | + |
| 228 | + def stop(self) -> None: |
| 229 | + super().stop() |
| 230 | + self._source.stop() |
| 231 | + |
| 232 | + |
| 233 | +class LocalStreamSource(StreamSource): |
| 234 | + """Stream source for locally captured RTSP/RTMP camera streams. |
| 235 | +
|
| 236 | + Unlike RTSPSource (where the server captures the RTSP stream), this source |
| 237 | + captures the stream locally using aiortc's MediaPlayer (FFmpeg-based) and |
| 238 | + sends frames to the server via WebRTC, similar to WebcamSource. |
| 239 | +
|
| 240 | + Supported protocols: |
| 241 | + - RTSP: rtsp://host/path or rtsps://host/path |
| 242 | + - RTMP: rtmp://host/path or rtmps://host/path |
| 243 | +
|
| 244 | + Use this when: |
| 245 | + - The camera is only accessible from the client machine (e.g., local network) |
| 246 | + - You want to preprocess frames before sending to the server |
| 247 | + - The server cannot access the stream URL directly |
| 248 | + """ |
| 249 | + |
| 250 | + # Supported URL schemes |
| 251 | + SUPPORTED_SCHEMES = ("rtsp://", "rtsps://", "rtmp://", "rtmps://") |
| 252 | + |
| 253 | + def __init__(self, url: str): |
| 254 | + """Initialize local stream source. |
| 255 | +
|
| 256 | + Args: |
| 257 | + url: Stream URL. Supported formats: |
| 258 | + - RTSP: "rtsp://host/stream" or "rtsps://host/stream" |
| 259 | + - RTMP: "rtmp://host/stream" or "rtmps://host/stream" |
| 260 | + Credentials can be included: "rtsp://user:pass@host/stream" |
| 261 | + """ |
| 262 | + if not url.startswith(self.SUPPORTED_SCHEMES): |
| 263 | + raise InvalidParameterError( |
| 264 | + f"Invalid stream URL: {url}. " |
| 265 | + f"Must start with one of: {', '.join(self.SUPPORTED_SCHEMES)}" |
| 266 | + ) |
| 267 | + self.url = url |
| 268 | + self._player: Optional[MediaPlayer] = None |
| 269 | + |
| 270 | + async def configure_peer_connection(self, pc: RTCPeerConnection) -> None: |
| 271 | + """Create MediaPlayer for stream and add video track to peer connection.""" |
| 272 | + |
| 273 | + if self.url.startswith(("rtsp://", "rtsps://")): |
| 274 | + self._player = await asyncio.to_thread( |
| 275 | + MediaPlayer, |
| 276 | + self.url, |
| 277 | + format="rtsp", |
| 278 | + options={ |
| 279 | + "rtsp_transport": "tcp", |
| 280 | + "rtsp_flags": "prefer_tcp", |
| 281 | + "stimeout": "5000000", # 5s RTSP socket timeout |
| 282 | + "timeout": "5000000", # 5s TCP connection timeout |
| 283 | + }, |
| 284 | + ) |
| 285 | + else: |
| 286 | + self._player = await asyncio.to_thread( |
| 287 | + MediaPlayer, |
| 288 | + self.url, |
| 289 | + options={ |
| 290 | + "rw_timeout": "5000000", # 5s socket timeout |
| 291 | + }, |
| 292 | + ) |
| 293 | + |
| 294 | + if self._player.video is None: |
| 295 | + raise RuntimeError(f"No video track available from stream: {self.url}") |
| 296 | + |
| 297 | + # Wrap in a pacing track — MediaPlayer does not pace RTSP frames |
| 298 | + # (RTSP is in REAL_TIME_FORMATS so _throttle_playback is False). |
| 299 | + # Without pacing the RTP sender bursts all packets at once, |
| 300 | + # overflowing the receiver's jitter buffer → truncated VP8 frames. |
| 301 | + self._paced_track = _PacedTrack(self._player.video) |
| 302 | + pc.addTrack(self._paced_track) |
| 303 | + |
| 304 | + def get_initialization_params(self, config: "StreamConfig") -> Dict[str, Any]: |
| 305 | + """Return empty params - stream is captured locally, not by server.""" |
| 306 | + return {} |
| 307 | + |
| 308 | + async def cleanup(self) -> None: |
| 309 | + """Stop the paced track and MediaPlayer.""" |
| 310 | + if hasattr(self, "_paced_track") and self._paced_track: |
| 311 | + self._paced_track.stop() |
| 312 | + self._paced_track = None |
| 313 | + if self._player: |
| 314 | + if self._player.video: |
| 315 | + self._player.video.stop() |
| 316 | + self._player = None |
| 317 | + |
| 318 | + |
184 | 319 | class RTSPSource(StreamSource): |
185 | 320 | """Stream source for RTSP camera streams. |
186 | 321 |
|
|
0 commit comments