-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmux.py
More file actions
2749 lines (2291 loc) · 126 KB
/
Copy pathmux.py
File metadata and controls
2749 lines (2291 loc) · 126 KB
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import cv2
import numpy as np
from dataclasses import dataclass, field
from typing import Dict, Optional, Tuple
from enum import Enum, auto
import logging
import mediapipe as mp
import os
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
import time
import datetime
import yaml # Add import for yaml to load secrets
import gc # Explicit garbage collection
import weakref # For weak references
import math # Add import for math functions
import subprocess # Add import for subprocess to run caffeinate
import atexit # Add import for atexit to ensure cleanup
import threading
from pathlib import Path
import queue # Add this import for the thread-safe queue
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(message)s')
log = logging.getLogger(__name__)
# Initialize GStreamer once
Gst.init(None)
class RetryManager:
"""Manages connection retry state for cameras"""
def __init__(self, max_retries: int = 10, base_retry_interval: float = 1.0, max_retry_interval: float = 30.0):
self.max_retries = max_retries
self.base_retry_interval = base_retry_interval
self.max_retry_interval = max_retry_interval
self.retry_states: Dict[str, Dict] = {} # camera_name -> retry state
def get_retry_state(self, camera_name: str) -> Dict:
"""Get or create retry state for a camera"""
if camera_name not in self.retry_states:
self.retry_states[camera_name] = {
'retry_count': 0,
'next_retry_time': 0,
'connection_lost': False,
'last_retry_time': 0 # Track when we last attempted a retry
}
return self.retry_states[camera_name]
def handle_connection_loss(self, camera_name: str, current_time: float) -> None:
"""Handle connection loss and setup retry timing"""
state = self.get_retry_state(camera_name)
if not state['connection_lost']:
state['connection_lost'] = True
state['retry_count'] += 1
state['next_retry_time'] = current_time + self.get_retry_interval(state['retry_count'])
state['last_retry_time'] = current_time
log.debug(f"Connection loss for {camera_name}, retry count: {state['retry_count']}")
def should_retry(self, camera_name: str, current_time: float) -> bool:
"""Check if it's time to retry connection"""
state = self.get_retry_state(camera_name)
return (state['connection_lost'] and
state['retry_count'] < self.max_retries and
current_time >= state['next_retry_time'])
def prepare_next_retry(self, camera_name: str, current_time: float) -> None:
"""Prepare for the next retry attempt"""
state = self.get_retry_state(camera_name)
# Only increment retry count if this is a new retry attempt
if current_time - state['last_retry_time'] > self.base_retry_interval:
state['retry_count'] += 1
state['last_retry_time'] = current_time
state['next_retry_time'] = current_time + self.get_retry_interval(state['retry_count'])
retry_interval = self.get_retry_interval(state['retry_count'])
log.info(f"Attempting reconnection to {camera_name} (attempt {state['retry_count']}/{self.max_retries}, next retry in {retry_interval:.1f}s)")
def get_retry_interval(self, retry_count: int) -> float:
"""Calculate retry interval using exponential backoff"""
interval = self.base_retry_interval * (2 ** retry_count)
return min(interval, self.max_retry_interval)
def reset_retry_state(self, camera_name: str) -> None:
"""Reset retry state for a camera after successful connection"""
state = self.get_retry_state(camera_name)
state['retry_count'] = 0
state['connection_lost'] = False
state['next_retry_time'] = 0
state['last_retry_time'] = 0
log.debug(f"Reset retry state for {camera_name}")
def cleanup(self, camera_name: str) -> None:
"""Clean up retry state for a camera"""
if camera_name in self.retry_states:
del self.retry_states[camera_name]
log.debug(f"Cleaned up retry state for {camera_name}")
@dataclass
class Camera:
url: str
name: str
resolution: Tuple[int, int] = (1920, 1080) # Target resolution
motion_res: Tuple[int, int] = (256, 256)
detection_res: Tuple[int, int] = (256, 256)
motion_threshold: float = 0.1
cooldown: int = 0
previous_frame: Optional[np.ndarray] = None # for motion detection
face_count: int = 0 # number of faces currently detected
motion_score: float = 0 # amount of motion (0-1)
active: bool = False
last_active_time: float = 0 # timestamp when camera last became active
main_camera: bool = False # is this the main camera in PiP mode?
manual_main: bool = False # manually selected as main camera
pipeline: Optional[Gst.Pipeline] = None
sink: Optional[Gst.Element] = None
last_frame_time: float = 0 # timestamp of last received frame
connection_lost: bool = False # flag for connection status
frame_rate: float = 30.0 # calculated frame rate
last_frame: Optional[np.ndarray] = None
input_resolution: Optional[Tuple[int, int]] = None # Actual input resolution
aspect_ratio: float = 16/9 # Default aspect ratio
is_vertical: bool = False # Flag for vertical orientation
frozen_frame: Optional[np.ndarray] = None # Last frame when connection was lost
frozen_frame_time: float = 0 # Time when the frame was frozen
# Frame rate calculation
_frame_times: list[float] = field(default_factory=list) # Store last N frame timestamps
_max_frame_times: int = 30 # Keep last 30 frames for calculation (0.5s at 60fps)
_last_fps_update: float = 0 # Last time we updated the FPS display
_fps_update_interval: float = 0.5 # Update FPS display every 0.5 seconds
# Bandwidth tracking
_bandwidth_samples: list[float] = field(default_factory=list) # Store bandwidth samples
_max_bandwidth_samples: int = 20 # Keep last 20 samples (10 seconds at 0.5s intervals)
_last_bandwidth_update: float = 0 # Last time we updated bandwidth
_bandwidth_update_interval: float = 0.5 # Update bandwidth every 0.5 seconds
_last_frame_size: int = 0 # Size of last frame in bytes
_bandwidth: float = 0.0 # Current bandwidth in kbps
# Memory management
_last_frame: Optional[np.ndarray] = None
def update_input_resolution(self, width: int, height: int) -> None:
"""Update the input resolution and calculate aspect ratio"""
self.input_resolution = (width, height)
self.aspect_ratio = width / height
# Detect vertical orientation (aspect ratio < 1)
self.is_vertical = self.aspect_ratio < 1
def get_scaled_resolution(self, target_width: int) -> Tuple[int, int]:
"""Calculate scaled resolution maintaining aspect ratio"""
if not self.input_resolution:
return (target_width, int(target_width / self.aspect_ratio))
# For vertical videos, scale based on height instead of width
if self.is_vertical:
target_height = target_width # Use full height
scaled_width = int(target_height * self.aspect_ratio)
return (scaled_width, target_height)
else:
# For horizontal videos, scale based on width
target_height = int(target_width / self.aspect_ratio)
return (target_width, target_height)
@property
def last_frame(self) -> Optional[np.ndarray]:
return self._last_frame
@last_frame.setter
def last_frame(self, frame: Optional[np.ndarray]):
self._last_frame = frame
def update_frame_rate(self, current_time: float) -> None:
"""Update frame rate calculation using a rolling window"""
# Add current frame time
self._frame_times.append(current_time)
# Keep only the last N frame times
if len(self._frame_times) > self._max_frame_times:
self._frame_times.pop(0)
# Update FPS display periodically
if current_time - self._last_fps_update >= self._fps_update_interval:
if len(self._frame_times) >= 2:
# Calculate average time between frames
time_diffs = [self._frame_times[i] - self._frame_times[i-1]
for i in range(1, len(self._frame_times))]
avg_time = sum(time_diffs) / len(time_diffs)
# Calculate FPS (avoid division by zero)
if avg_time > 0:
self.frame_rate = 1.0 / avg_time
else:
self.frame_rate = 0.0
self._last_fps_update = current_time
def update_bandwidth(self, frame_size: int, current_time: float) -> None:
"""Update bandwidth calculation"""
self._last_frame_size = frame_size
# Update bandwidth periodically
if current_time - self._last_bandwidth_update >= self._bandwidth_update_interval:
# Calculate bandwidth in kbps
if len(self._frame_times) >= 2:
time_diff = self._frame_times[-1] - self._frame_times[-2]
if time_diff > 0:
# Convert bytes to kbps
kbps = (frame_size * 8) / (time_diff * 1000)
self._bandwidth_samples.append(kbps)
# Keep only the last N samples
if len(self._bandwidth_samples) > self._max_bandwidth_samples:
self._bandwidth_samples.pop(0)
# Calculate average bandwidth
self._bandwidth = sum(self._bandwidth_samples) / len(self._bandwidth_samples)
elif self.connection_lost or current_time - self.last_frame_time > 0.5:
# Continue sampling zeros during disconnection or frame drops
self._bandwidth_samples.append(0)
if len(self._bandwidth_samples) > self._max_bandwidth_samples:
self._bandwidth_samples.pop(0)
self._bandwidth = 0
self._last_bandwidth_update = current_time
def draw_bandwidth_graph(self, frame: np.ndarray, x: int, y: int, width: int, height: int) -> None:
"""Draw a bandwidth area chart on the frame"""
if not self._bandwidth_samples:
return
# Create graph background
cv2.rectangle(frame, (x, y), (x + width, y + height), (0, 0, 0), -1)
cv2.rectangle(frame, (x, y), (x + width, y + height), (100, 100, 100), 1)
# Find max bandwidth for scaling
max_bw = max(self._bandwidth_samples) if self._bandwidth_samples else 1000
max_bw = max(max_bw, 1000) # Minimum scale of 1000 kbps
# Create points for the graph
points = []
for i, bw in enumerate(self._bandwidth_samples):
x_pos = x + int((i / len(self._bandwidth_samples)) * width)
y_pos = y + height - int((bw / max_bw) * height)
points.append((x_pos, y_pos))
if len(points) > 1:
# Create a polygon for the area chart
polygon_points = points.copy()
# Add bottom corners to close the polygon
polygon_points.append((x + width, y + height))
polygon_points.append((x, y + height))
# Use red for disconnected state, green for connected
color = (0, 0, 255) if self.connection_lost else (0, 100, 0)
line_color = (0, 255, 255) if self.connection_lost else (0, 255, 0)
# Fill the area
cv2.fillPoly(frame, [np.array(polygon_points, dtype=np.int32)], color)
# Draw the top line with anti-aliasing
for i in range(len(points) - 1):
cv2.line(frame, points[i], points[i+1], line_color, 1, cv2.LINE_AA)
def cleanup(self):
"""Clean up resources when camera is no longer needed"""
self.previous_frame = None
self._last_frame = None
self.frozen_frame = None # Clear frozen frame
self._frame_times.clear() # Clear frame time history
self._bandwidth_samples.clear() # Clear bandwidth history
if self.pipeline:
self.pipeline.set_state(Gst.State.NULL)
self.sink = None
self.pipeline = None
def get_retry_interval(self) -> float:
"""Calculate retry interval using exponential backoff"""
# Start with base interval and double with each retry
interval = self.base_retry_interval * (2 ** self.retry_count)
# Cap at max_retry_interval
return min(interval, self.max_retry_interval)
def handle_connection_loss(self, current_time: float) -> None:
"""Handle connection loss and setup retry timing"""
if not self.connection_lost:
# Immediately mark as inactive and lost connection
self.active = False
self.connection_lost = True
self.face_count = 0
self.motion_score = 0
self.frame_rate = 0
self._bandwidth = 0
self._frame_times.clear()
# Don't reset retry count here, only increment
self.retry_count += 1
self.next_retry_time = current_time + self.get_retry_interval()
# If this was the main camera, remove that status
if self.main_camera:
self.main_camera = False
self.manual_main = False # Also remove manual lock
# Store frozen frame if we have a last frame
if self.last_frame is not None:
try:
gray = cv2.cvtColor(self.last_frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (15, 15), 20)
self.frozen_frame = cv2.cvtColor(blurred, cv2.COLOR_GRAY2BGR)
self.frozen_frame_time = current_time
except Exception as e:
log.error(f"Error creating frozen frame for {self.name}: {e}")
# If we can't create a frozen frame, just use the last frame
self.frozen_frame = self.last_frame.copy()
self.frozen_frame_time = current_time
def should_retry(self, current_time: float) -> bool:
"""Check if it's time to retry connection"""
return (self.connection_lost and
self.retry_count < self.max_retries and
current_time >= self.next_retry_time)
def prepare_next_retry(self, current_time: float) -> None:
"""Prepare for the next retry attempt"""
self.next_retry_time = current_time + self.get_retry_interval()
retry_interval = self.get_retry_interval()
log.info(f"Attempting reconnection to {self.name} (attempt {self.retry_count}/{self.max_retries}, next retry in {retry_interval:.1f}s)")
class ViewMode(Enum):
INPUT = auto() # show input view in grid
OUTPUT = auto() # output mode
class FramePool:
"""Memory pool for frame buffers to avoid constant allocations"""
def __init__(self, max_frames=5):
self.available = []
self.max_frames = max_frames
self.size_map = {} # Track frame sizes
def get_frame(self, shape, dtype=np.uint8):
"""Get a frame from the pool or create a new one if needed"""
key = (shape, dtype)
if key in self.size_map:
frames = self.size_map[key]
if frames:
return frames.pop()
# If we reach here, we need to create a new frame
return np.zeros(shape, dtype=dtype)
def return_frame(self, frame):
"""Return a frame to the pool"""
if frame is None:
return
key = (frame.shape, frame.dtype)
if key not in self.size_map:
self.size_map[key] = []
frames = self.size_map[key]
# Only keep a limited number of frames of each size
if len(frames) < self.max_frames:
frames.append(frame)
class GstBuffer:
"""Wrapper for GStreamer buffer management"""
def __init__(self, size=0):
self.buffer = None
self.size = 0
if size > 0:
self.ensure_size(size)
def ensure_size(self, size):
"""Ensure the buffer is at least the requested size"""
if self.buffer is None or self.size < size:
self.buffer = bytearray(size)
self.size = size
return True
return False
def get_view(self, size=None):
"""Get a memory view of the buffer"""
if size is None or size == self.size:
return memoryview(self.buffer)
else:
return memoryview(self.buffer)[:size]
def cleanup(self):
"""Release the buffer"""
self.buffer = None
self.size = 0
class WorkshopStream:
def __init__(self, debug: bool = False):
self.cameras: Dict[str, Camera] = {}
self.output_frame: Optional[np.ndarray] = None
self.clean_frame_for_recording: Optional[np.ndarray] = None
self.running = False
self.debug = debug
self.view_mode = ViewMode.OUTPUT
# Add task manager for camera tasks
self.camera_tasks: Dict[str, asyncio.Task] = {}
self.main_task: Optional[asyncio.Task] = None
# Add thread-safe camera operation queue for RTMP server
self.camera_ops_queue = queue.Queue()
# Add caffeinate process reference
self._caffeinate_process = None
# Register cleanup function to ensure sleep prevention is disabled on exit
atexit.register(self._restore_sleep)
# Recording related attributes
self.recording = False
self.recording_pipeline = None
self.recording_src = None
self.recording_paused = False
self.auto_recording = False
self.frame_count = 0 # Initialize frame counter
# Streaming related attributes
self.streaming = False
self.streaming_pipeline = None
self.streaming_src = None
# Memory management
self.frame_pool = FramePool()
# Load secrets
self.twitch_stream_key = self._load_twitch_stream_key()
# Initialize retry manager
self.retry_manager = RetryManager()
# Initialize mediapipe detector
BaseOptions = mp.tasks.BaseOptions
Detector = mp.tasks.vision.ObjectDetector
DetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode
# Load lock icon for overlays
self.pushpin_icon = cv2.imread('icons8-lock-30.png', cv2.IMREAD_UNCHANGED)
if self.pushpin_icon is None:
log.warning('Could not load lock.png for overlays.')
# Create detector for person detection
options = DetectorOptions(
base_options=BaseOptions(model_asset_path='efficientdet_lite0.tflite'),
running_mode=VisionRunningMode.IMAGE,
score_threshold=0.29,
category_allowlist=['person'])
self.detector = Detector.create_from_options(options)
# Add timestamp for last tab press
self.last_tab_time = 0
self.tab_cooldown = 5.0 # 5 seconds cooldown
# RTMP server integration
self.rtmp_server = None
self.rtmp_server_process = None
self.rtmp_notify_fd = None
self.rtmp_notify_thread = None
# Add connection tracking for RTMP streams
self.rtmp_connections = {} # Map IP:port -> camera_name
def _start_rtmp_server(self):
"""Start the RTMP server in the background"""
try:
# Import here to avoid circular imports
from rtmp_srt_server import get_mediamtx, create_config, run_server
# Get MediaMTX binary
executable = get_mediamtx()
# Create config file
config_path = Path.cwd() / "mediamtx.yml"
create_config(config_path)
# Start server in background with output capture
self.rtmp_server_process = subprocess.Popen(
[str(executable), str(config_path)],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
bufsize=1 # Line buffered
)
# Start a thread to read and log the server output
def log_server_output():
while self.running and self.rtmp_server_process:
try:
line = self.rtmp_server_process.stdout.readline()
if line:
log.info(f"[RTMP Server] {line.strip()}")
# Parse RTMP server messages for camera lifecycle events
if "is publishing to path" in line:
# Extract path from message
# Example: "is publishing to path 'live/mystream', 2 tracks (H264, MPEG-4 Audio)"
try:
path = line.split("path '")[1].split("'")[0]
rtsp_url = f"rtsp://127.0.0.1:8554/{path}"
camera_name = f"RTMP-{path.split('/')[-1]}"
# Extract connection info - looks like [conn 192.168.1.155:50058]
if "[conn " in line:
conn_info = line.split("[conn ")[1].split("]")[0]
# Store the association between connection and camera
self.rtmp_connections[conn_info] = camera_name
log.info(f"Tracking RTMP connection {conn_info} for camera {camera_name}")
# Add the camera operation to the thread-safe queue
self.camera_ops_queue.put(("add", camera_name, rtsp_url))
log.info(f"Queued add operation for camera: {camera_name}")
except Exception as e:
log.error(f"Error parsing RTMP publish message: {e}")
elif "closed: EOF" in line and "RTMP" in line:
# RTMP connection closed, find and remove the corresponding camera
try:
# Extract connection info from message
# Example: "[conn 192.168.1.155:50058] closed: EOF"
if "[conn " in line:
conn_info = line.split("[conn ")[1].split("]")[0]
# Find the camera associated with this connection
camera_name = self.rtmp_connections.get(conn_info)
if camera_name:
# Add the remove operation to the queue
self.camera_ops_queue.put(("remove", camera_name))
log.info(f"RTMP connection {conn_info} closed, queued remove operation for camera: {camera_name}")
# Remove from connection tracking
del self.rtmp_connections[conn_info]
else:
# Fallback to the old method if we don't have tracking info
rtmp_cameras = [name for name in self.cameras.keys() if name.startswith("RTMP-")]
if len(rtmp_cameras) == 1:
camera_name = rtmp_cameras[0]
# Add the remove operation to the queue
self.camera_ops_queue.put(("remove", camera_name))
log.info(f"Queued remove operation for camera: {camera_name} (using fallback method)")
except Exception as e:
log.error(f"Error handling RTMP close message: {e}")
elif self.rtmp_server_process.poll() is not None:
break
except Exception as e:
log.error(f"Error reading RTMP server output: {e}")
break
threading.Thread(target=log_server_output, daemon=True).start()
log.info("RTMP server started")
except Exception as e:
log.error(f"Failed to start RTMP server: {e}")
raise
async def start(self) -> None:
"""Start the stream processing with explicit memory management"""
log.info("Starting workshop stream")
self.running = True
# Prevent sleep when starting
self._prevent_sleep()
# Start RTMP server
self._start_rtmp_server()
# Create tasks for existing cameras
for camera in self.cameras.values():
self._start_camera_task(camera)
# Add debug viewer task if debug mode is enabled
if self.debug:
self.main_task = asyncio.create_task(self._run_debug_viewer())
try:
# Wait for the main task (debug viewer) to complete
if self.main_task:
await self.main_task
except (KeyboardInterrupt, asyncio.CancelledError):
log.info("Shutting down...")
self.running = False
# Cancel all camera tasks
for task in self.camera_tasks.values():
if not task.done():
task.cancel()
# Cancel main task if it exists
if self.main_task and not self.main_task.done():
self.main_task.cancel()
self.stop()
async def _run_debug_viewer(self):
"""Run debug viewer with memory management"""
try:
while self.running:
# Process any pending camera operations from RTMP server
self._process_camera_ops()
# Update bandwidth for input view, including disconnected ones
current_time = time.time()
for camera in self.cameras.values():
if camera.connection_lost:
# Force bandwidth update for disconnected cameras
camera.update_bandwidth(0, current_time)
# Create debug view
view = await self._create_debug_view()
# Handle auto-recording based on camera activity
self._handle_auto_recording()
# Handle recording and streaming
self._handle_recording_and_streaming(view)
# Show the view
cv2.imshow('Debug View', view)
# Process keyboard input
key = cv2.waitKey(1) & 0xFF
self._handle_keyboard_input(key)
# Return view frame to pool
self.frame_pool.return_frame(view)
# Run garbage collection periodically
if self.frame_count % 600 == 0: # Every 10 seconds at 60fps
gc.collect()
# Sleep to maintain frame rate
await asyncio.sleep(1/60)
finally:
cv2.destroyAllWindows()
if self.recording:
self.stop_recording()
if self.streaming:
self.stop_streaming()
def _process_camera_ops(self):
"""Process camera operations from the thread-safe queue"""
# Process up to 10 operations at a time to prevent blocking
for _ in range(10):
try:
# Get operation from queue (non-blocking)
op_type, *args = self.camera_ops_queue.get_nowait()
if op_type == "add":
camera_name, rtsp_url = args
# Add the camera if it doesn't exist
if camera_name not in self.cameras:
log.info(f"Processing add operation: {camera_name} from {rtsp_url}")
self.add_camera(rtsp_url, camera_name)
elif op_type == "remove":
camera_name = args[0]
# Remove the camera if it exists
if camera_name in self.cameras:
log.info(f"Processing remove operation: {camera_name}")
self.remove_camera(camera_name)
# Mark task as done
self.camera_ops_queue.task_done()
except queue.Empty:
# No more operations to process
break
except Exception as e:
log.error(f"Error processing camera operation: {e}")
def _start_camera_task(self, camera: Camera) -> None:
"""Start a task for a camera if it doesn't already have one"""
if camera.name not in self.camera_tasks or self.camera_tasks[camera.name].done():
self.camera_tasks[camera.name] = asyncio.create_task(self._capture_frames(camera))
log.info(f"Started task for camera: {camera.name}")
def _stop_camera_task(self, camera_name: str) -> None:
"""Stop a camera's task if it exists"""
if camera_name in self.camera_tasks:
task = self.camera_tasks[camera_name]
if not task.done():
task.cancel()
del self.camera_tasks[camera_name]
log.info(f"Stopped task for camera: {camera_name}")
def add_camera(self, url: str, name: str) -> None:
"""Add a new camera to the stream"""
camera = Camera(url=url, name=name)
self.cameras[name] = camera
# Initialize retry state for the new camera
self.retry_manager.get_retry_state(name)
log.info(f"Added camera: {name} @ {url}")
# Start a task for the new camera if the stream is running
if self.running:
self._start_camera_task(camera)
def remove_camera(self, name: str) -> None:
"""Remove a camera from the stream"""
if name in self.cameras:
# Stop the camera's task
self._stop_camera_task(name)
# Clean up camera resources
camera = self.cameras[name]
camera.cleanup()
# Remove from cameras dict
del self.cameras[name]
# Clean up retry state
self.retry_manager.cleanup(name)
log.info(f"Removed camera: {name}")
# If this was the main camera, select another one
if camera.main_camera:
new_main = self._select_main_camera()
if new_main:
log.info(f"Switched main camera to {new_main} after removing {name}")
else:
log.warning("No active cameras available to switch to")
def stop(self) -> None:
"""Stop the stream processing and clean up resources"""
self.running = False
# Stop recording and streaming
if self.recording:
self.stop_recording()
if self.streaming:
self.stop_streaming()
# Clean up cameras
for camera in self.cameras.values():
camera.cleanup()
# Clear connection tracking
self.rtmp_connections.clear()
# Stop RTMP server
if self.rtmp_server_process:
try:
self.rtmp_server_process.terminate()
self.rtmp_server_process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.rtmp_server_process.kill()
except Exception as e:
log.error(f"Error stopping RTMP server: {e}")
# Restore sleep behavior
self._restore_sleep()
# Clean up other resources
if self.debug:
cv2.destroyAllWindows()
# Clear references to large objects
self.clean_frame_for_recording = None
self.output_frame = None
# Run garbage collection
gc.collect()
def _load_twitch_stream_key(self) -> str:
"""Load Twitch stream key from secrets.yaml file"""
try:
with open('secrets.yaml', 'r') as f:
secrets = yaml.safe_load(f)
stream_key = secrets.get('twitch_stream_key', '')
if not stream_key:
log.warning("Twitch stream key not found in secrets.yaml. Streaming will not work.")
return stream_key
except Exception as e:
log.error(f"Failed to load Twitch stream key: {e}")
return ''
def _create_camera_pipeline(self, camera: Camera) -> None:
"""Create and configure GStreamer pipeline for a camera using uridecodebin"""
# Create GStreamer pipeline based on camera URL type
if camera.url.isdigit(): # USB webcam
pipeline_str = (
f'avfvideosrc device-index={camera.url} ! '
'video/x-raw,format=YUY2,width=1920,height=1080,framerate=60/1 ! '
'videoconvert ! video/x-raw,format=BGR ! '
'appsink name=sink emit-signals=True max-buffers=4096 drop=False'
)
else: # RTSP/HTTP stream
# pipeline_str = (
# f'uridecodebin uri={camera.url} name=src ! '
# 'queue max-size-buffers=4096 max-size-bytes=0 max-size-time=0 ! '
# 'videoconvert ! video/x-raw,format=BGR ! '
# 'appsink name=sink emit-signals=True max-buffers=4096 drop=False'
# )
# os.environ["GST_RTSP_TRANSPORT"] = "udp"
pipeline_str = (
f'uridecodebin uri={camera.url} name=src '
'src. ! queue max-size-time=10000000000 leaky=downstream ! '
'videoconvert ! videorate max-rate=30 ! '
'videoscale method=lanczos ! video/x-raw,width=1280,height=720,format=BGR ! '
'videobalance contrast=1.1 brightness=0.05 ! '
'appsink name=sink emit-signals=True drop=False sync=false '
'src. ! queue max-size-time=10000000000 leaky=downstream ! '
'audioconvert ! audioresample quality=10 ! volume volume=1.5 ! '
'autoaudiosink sync=false'
)
# GST_RTSP_TRANSPORT=tcp gst-launch-1.0 uridecodebin uri=rtsp://192.168.1.155:8554/live name=src \
# src. ! queue max-size-time=10000000000 leaky=downstream ! videoconvert ! videorate max-rate=30 ! \
# videoscale method=lanczos ! video/x-raw,width=1280,height=720 ! videobalance contrast=1.1 brightness=0.05 ! \
# autovideosink sync=false \
# src. ! queue max-size-time=10000000000 leaky=downstream ! \
# audioconvert ! audioresample quality=10 ! volume volume=1.5 ! \
# autoaudiosink sync=false
log.debug(f"Creating pipeline for {camera.name}: {pipeline_str}")
# Create and store the pipeline in the camera object
camera.pipeline = Gst.parse_launch(pipeline_str)
camera.sink = camera.pipeline.get_by_name('sink')
# For network streams, we need to handle dynamic pad creation
if not camera.url.isdigit():
src = camera.pipeline.get_by_name('src')
def on_pad_added(element, pad):
# Get pad capabilities
caps = pad.query_caps(None)
if caps:
# Check if this is a video pad
if caps.is_subset(Gst.Caps.from_string('video/x-raw')):
# Get the queue element
queue = camera.pipeline.get_by_name('queue0')
if queue:
# Link the pad to the queue
pad.link(queue.get_static_pad('sink'))
log.debug(f"Linked video pad for {camera.name}")
# Connect to pad-added signal
src.connect('pad-added', on_pad_added)
# Add bus watch to monitor pipeline state changes and errors
bus = camera.pipeline.get_bus()
bus.add_signal_watch()
def on_bus_message(bus, message):
t = message.type
if t == Gst.MessageType.ERROR:
err, debug = message.parse_error()
log.error(f"Pipeline error for {camera.name}: {err.message}")
log.debug(f"Debug info: {debug}")
camera.connection_lost = True
elif t == Gst.MessageType.STATE_CHANGED:
old_state, new_state, pending_state = message.parse_state_changed()
if message.src == camera.pipeline:
log.debug(f"Pipeline state changed for {camera.name}: {old_state.value_nick} -> {new_state.value_nick}")
elif t == Gst.MessageType.EOS:
log.warning(f"End of stream for {camera.name}")
camera.connection_lost = True
return True
bus.connect('message', on_bus_message)
async def _capture_frames(self, camera: Camera) -> None:
"""Capture frames from a camera and detect people"""
detection_counter = 0
while self.running:
try:
# Create GStreamer pipeline for this camera
self._create_camera_pipeline(camera)
# Create a reference to self that won't prevent garbage collection
stream_ref = weakref.ref(self)
# Flag to track if we've received the first frame
first_frame_received = False
connection_start_time = time.time()
connection_timeout = 5.0 # 5 seconds timeout for initial connection
# Setup frame callback
def on_new_sample(appsink):
try:
# Get the stream reference
stream = stream_ref()
if not stream:
return Gst.FlowReturn.ERROR
current_time = time.time()
# Get the sample from appsink
sample = appsink.emit("pull-sample")
if not sample:
return Gst.FlowReturn.ERROR
# Get the buffer from the sample
buffer = sample.get_buffer()
if not buffer:
return Gst.FlowReturn.ERROR
# Map the buffer for reading
success, map_info = buffer.map(Gst.MapFlags.READ)
if not success:
return Gst.FlowReturn.ERROR
try:
# Update camera state
camera.last_frame_time = current_time
if camera.connection_lost:
# Reset retry state when we get a frame after being disconnected
stream.retry_manager.reset_retry_state(camera.name)
camera.connection_lost = False # We got a frame, so connection is not lost
# Mark that we've received our first frame
nonlocal first_frame_received
first_frame_received = True
# Update frame rate calculation
camera.update_frame_rate(current_time)
# Get caps to determine actual resolution
caps = sample.get_caps()
if caps:
structure = caps.get_structure(0)
if structure:
width = structure.get_value('width')
height = structure.get_value('height')
if width and height:
camera.update_input_resolution(width, height)
# Update bandwidth calculation
frame_size = buffer.get_size()
camera.update_bandwidth(frame_size, current_time)
# Get a reusable frame from the pool
old_frame = camera.last_frame
# Create frame with actual input resolution
if camera.input_resolution:
camera.last_frame = np.ndarray(
shape=(camera.input_resolution[1], camera.input_resolution[0], 3),
dtype=np.uint8,
buffer=map_info.data
)
else:
# Fallback to target resolution if input resolution not known
camera.last_frame = np.ndarray(
shape=(camera.resolution[1], camera.resolution[0], 3),
dtype=np.uint8,
buffer=map_info.data
)
# Return old frame to the pool
if old_frame is not None:
stream.frame_pool.return_frame(old_frame)
# Handle detection on a subset of frames
nonlocal detection_counter
detection_counter += 1
if detection_counter % 10 == 0: # Every 10th frame
try:
# Get a frame for detection resizing
small_frame = cv2.resize(camera.last_frame, camera.detection_res)
# Convert to RGB for MediaPipe
small_frame_rgb = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
# Create MediaPipe image
mp_image = mp.Image(
image_format=mp.ImageFormat.SRGB,
data=small_frame_rgb
)
# Run detection
results = stream.detector.detect(mp_image)
# Update camera state
camera.face_count = len(results.detections)
if camera.face_count > 0:
if not camera.active:
log.info(f"Camera {camera.name} became active")
camera.active = True
camera.cooldown = 30
camera.last_active_time = time.time()
elif camera.cooldown > 0:
camera.cooldown -= 1
else:
if camera.active:
log.info(f"Camera {camera.name} became inactive")
camera.active = False
camera.face_count = 0