|
12 | 12 | RTCConfiguration, |
13 | 13 | RTCIceServer, |
14 | 14 | MediaStreamTrack, |
15 | | - RTCDataChannel, |
16 | 15 | ) |
| 16 | +import threading |
| 17 | +import av |
17 | 18 | from aiortc.rtcrtpsender import RTCRtpSender |
18 | 19 | from aiortc.codecs import h264 |
19 | 20 | from pipeline import Pipeline |
20 | | -from utils import patch_loop_datagram |
| 21 | +from utils import patch_loop_datagram, StreamStats |
| 22 | +import time |
21 | 23 |
|
22 | 24 | logger = logging.getLogger(__name__) |
23 | 25 | logging.getLogger('aiortc.rtcrtpsender').setLevel(logging.WARNING) |
|
29 | 31 |
|
30 | 32 |
|
31 | 33 | class VideoStreamTrack(MediaStreamTrack): |
| 34 | + """video stream track that processes video frames using a pipeline. |
| 35 | +
|
| 36 | + Attributes: |
| 37 | + kind (str): The kind of media, which is "video" for this class. |
| 38 | + track (MediaStreamTrack): The underlying media stream track. |
| 39 | + pipeline (Pipeline): The processing pipeline to apply to each video frame. |
| 40 | + """ |
| 41 | + |
32 | 42 | kind = "video" |
33 | 43 |
|
34 | | - def __init__(self, track: MediaStreamTrack, pipeline): |
| 44 | + def __init__(self, track: MediaStreamTrack, pipeline: Pipeline): |
| 45 | + """Initialize the VideoStreamTrack. |
| 46 | +
|
| 47 | + Args: |
| 48 | + track: The underlying media stream track. |
| 49 | + pipeline: The processing pipeline to apply to each video frame. |
| 50 | + """ |
35 | 51 | super().__init__() |
36 | 52 | self.track = track |
37 | 53 | self.pipeline = pipeline |
38 | | - |
39 | | - async def recv(self): |
40 | | - frame = await self.track.recv() |
41 | | - return await self.pipeline(frame) |
| 54 | + self._frame_count = 0 |
| 55 | + self._start_time = time.monotonic() |
| 56 | + self._lock = threading.Lock() |
| 57 | + self._fps = 0.0 |
| 58 | + self._running = True |
| 59 | + self._start_fps_thread() |
| 60 | + |
| 61 | + def _start_fps_thread(self): |
| 62 | + """Start a separate thread to calculate FPS periodically.""" |
| 63 | + self.fps_thread = threading.Thread(target=self._calculate_fps_loop, daemon=True) |
| 64 | + self.fps_thread.start() |
| 65 | + |
| 66 | + def _calculate_fps_loop(self): |
| 67 | + """Loop to calculate FPS periodically.""" |
| 68 | + while self._running: |
| 69 | + time.sleep(1) # Calculate FPS every second. |
| 70 | + with self._lock: |
| 71 | + current_time = time.monotonic() |
| 72 | + time_diff = current_time - self._start_time |
| 73 | + if time_diff > 0: |
| 74 | + self._fps = self._frame_count / time_diff |
| 75 | + |
| 76 | + # Reset start_time and frame_count for the next interval. |
| 77 | + self._start_time = current_time |
| 78 | + self._frame_count = 0 |
| 79 | + |
| 80 | + def stop(self): |
| 81 | + """Stop the FPS calculation thread.""" |
| 82 | + self._running = False |
| 83 | + self.fps_thread.join() |
| 84 | + |
| 85 | + @property |
| 86 | + def fps(self) -> float: |
| 87 | + """Get the current output frames per second (FPS). |
| 88 | +
|
| 89 | + Returns: |
| 90 | + The current output FPS. |
| 91 | + """ |
| 92 | + with self._lock: |
| 93 | + return self._fps |
| 94 | + |
| 95 | + async def recv(self) -> av.VideoFrame: |
| 96 | + """Receive and process a video frame. Called by the WebRTC library when a frame |
| 97 | + is received. |
| 98 | +
|
| 99 | + Returns: |
| 100 | + The processed video frame. |
| 101 | + """ |
| 102 | + input_frame = await self.track.recv() |
| 103 | + processed_frame = await self.pipeline(input_frame) |
| 104 | + |
| 105 | + # Increment frame count for FPS calculation. |
| 106 | + with self._lock: |
| 107 | + self._frame_count += 1 |
| 108 | + |
| 109 | + return processed_frame |
42 | 110 |
|
43 | 111 |
|
44 | 112 | def force_codec(pc, sender, forced_codec): |
@@ -156,6 +224,10 @@ def on_track(track): |
156 | 224 | tracks["video"] = videoTrack |
157 | 225 | sender = pc.addTrack(videoTrack) |
158 | 226 |
|
| 227 | + # Store video track in app for stats. |
| 228 | + stream_id = track.id |
| 229 | + request.app["video_tracks"][stream_id] = videoTrack |
| 230 | + |
159 | 231 | codec = "video/H264" |
160 | 232 | force_codec(pc, sender, codec) |
161 | 233 |
|
@@ -207,6 +279,7 @@ async def on_startup(app: web.Application): |
207 | 279 | cwd=app["workspace"], disable_cuda_malloc=True, gpu_only=True |
208 | 280 | ) |
209 | 281 | app["pcs"] = set() |
| 282 | + app["video_tracks"] = {} |
210 | 283 |
|
211 | 284 |
|
212 | 285 | async def on_shutdown(app: web.Application): |
@@ -251,4 +324,9 @@ async def on_shutdown(app: web.Application): |
251 | 324 | app.router.add_post("/prompt", set_prompt) |
252 | 325 | app.router.add_get("/", health) |
253 | 326 |
|
| 327 | + # Add routes for getting stream statistics. |
| 328 | + stream_stats = StreamStats(app) |
| 329 | + app.router.add_get("/stats", stream_stats.get_stats) |
| 330 | + app.router.add_get("/stats/{stream_id}", stream_stats.get_stats_by_id) |
| 331 | + |
254 | 332 | web.run_app(app, host=args.host, port=int(args.port)) |
0 commit comments