-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.py
More file actions
1689 lines (1447 loc) · 63.8 KB
/
server.py
File metadata and controls
1689 lines (1447 loc) · 63.8 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 os, subprocess, threading, time, signal, pathlib, re, uuid, asyncio, queue
from urllib.request import urlopen, Request as UrlRequest
from urllib.error import URLError
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse, PlainTextResponse, RedirectResponse, StreamingResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import Dict, Set
import zmq
app = FastAPI()
# CORS middleware for frontend communication
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins (local network only)
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
OUTDIR = "/out"
os.makedirs(OUTDIR, exist_ok=True)
# --- Tunables (override via -e NAME=value) ---
IDLE_TIMEOUT = int(os.getenv("IDLE_TIMEOUT", "60"))
DEFAULT_UA = os.getenv("DEFAULT_UA", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128 Safari/537.36")
SOURCE_HEADERS = os.getenv("SOURCE_HEADERS", "")
AUDIO_SOURCE = int(os.getenv("AUDIO_SOURCE", "0")) # 0=IN1, 1=IN2, 2=mix
ENCODER_PREFERENCE = os.getenv("ENCODER_PREFERENCE", "auto").lower()
INSET_SCALE = int(os.getenv("INSET_SCALE", "640"))
INSET_MARGIN = int(os.getenv("INSET_MARGIN", "40"))
STANDBY_LABEL = os.getenv("STANDBY_LABEL", "Standby")
HLS_TIME = os.getenv("HLS_TIME", "1")
HLS_LIST_SIZE = os.getenv("HLS_LIST_SIZE", "8")
HLS_DELETE_THRESHOLD = os.getenv("HLS_DELETE_THRESHOLD", "2")
FONT = os.getenv("FONT", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf")
M3U_SOURCE = os.getenv("M3U_SOURCE", "http://127.0.0.1:9191/output/m3u?direct=true")
# Stream file size limit (in bytes) - restart FFmpeg when exceeded
# Default: 500MB to prevent unbounded growth
MAX_STREAM_SIZE = int(os.getenv("MAX_STREAM_SIZE", str(500 * 1024 * 1024)))
# ------------------------------------------------
# ========== Hardware Encoder Detection ==========
# Encoder configurations with optimal settings for each hardware type
ENCODER_CONFIGS = {
'nvidia': {
'name': 'NVIDIA NVENC',
'codec': 'h264_nvenc',
'test_args': ['-f', 'lavfi', '-i', 'nullsrc=s=256x256:d=0.1', '-c:v', 'h264_nvenc', '-f', 'null', '-'],
'encode_args': [
"-c:v", "h264_nvenc",
"-preset", "p5", "-rc", "vbr",
"-b:v", "6000k", "-maxrate", "6500k", "-bufsize", "12M",
"-spatial_aq", "1", "-aq-strength", "8",
"-pix_fmt", "yuv420p", "-r", "30", "-g", "60",
]
},
'intel': {
'name': 'Intel QuickSync',
'codec': 'h264_qsv',
'test_args': ['-f', 'lavfi', '-i', 'nullsrc=s=256x256:d=0.1', '-c:v', 'h264_qsv', '-f', 'null', '-'],
'encode_args': [
"-c:v", "h264_qsv",
"-preset", "medium", "-look_ahead", "1",
"-b:v", "6000k", "-maxrate", "6500k", "-bufsize", "12M",
"-pix_fmt", "yuv420p", "-r", "30", "-g", "60",
]
},
'amd': {
'name': 'AMD VAAPI',
'codec': 'h264_vaapi',
'test_args': ['-init_hw_device', 'vaapi=va:/dev/dri/renderD128', '-f', 'lavfi', '-i', 'nullsrc=s=256x256:d=0.1', '-vf', 'format=nv12,hwupload', '-c:v', 'h264_vaapi', '-f', 'null', '-'],
'encode_args': [
"-init_hw_device", "vaapi=va:/dev/dri/renderD128",
"-vf", "format=nv12,hwupload",
"-c:v", "h264_vaapi",
"-b:v", "6000k", "-maxrate", "6500k",
"-pix_fmt", "yuv420p", "-r", "30", "-g", "60",
]
},
'cpu': {
'name': 'CPU (libx264)',
'codec': 'libx264',
'test_args': ['-f', 'lavfi', '-i', 'nullsrc=s=256x256:d=0.1', '-c:v', 'libx264', '-f', 'null', '-'],
'encode_args': [
"-c:v", "libx264",
"-preset", "veryfast", "-tune", "zerolatency",
"-b:v", "6000k", "-maxrate", "6500k", "-bufsize", "12M",
"-pix_fmt", "yuv420p", "-r", "30", "-g", "60",
]
}
}
def test_encoder(encoder_type: str) -> bool:
"""
Test if a specific encoder is available and functional.
Args:
encoder_type: One of 'nvidia', 'intel', 'amd', 'cpu'
Returns:
True if encoder works, False otherwise
"""
if encoder_type not in ENCODER_CONFIGS:
return False
config = ENCODER_CONFIGS[encoder_type]
print(f" Testing {config['name']} ({config['codec']})...")
try:
# Run a quick encoding test with null output
result = subprocess.run(
['ffmpeg', '-hide_banner', '-loglevel', 'error'] + config['test_args'],
capture_output=True,
timeout=5
)
if result.returncode == 0:
print(f" ✓ {config['name']} is available and functional")
return True
else:
error_msg = result.stderr.decode('utf-8', errors='ignore').strip()
print(f" ✗ {config['name']} test failed: {error_msg[:100]}")
return False
except subprocess.TimeoutExpired:
print(f" ✗ {config['name']} test timed out")
return False
except FileNotFoundError:
print(f" ✗ FFmpeg not found")
return False
except Exception as e:
print(f" ✗ {config['name']} test error: {e}")
return False
def detect_encoder() -> str:
"""
Detect the best available hardware encoder based on ENCODER_PREFERENCE.
Returns:
encoder_type: One of 'nvidia', 'intel', 'amd', 'cpu'
"""
print("=" * 60)
print("Hardware Encoder Detection")
print("=" * 60)
print(f"Preference: {ENCODER_PREFERENCE}")
print()
# Define fallback chain (preference order)
fallback_chain = ['nvidia', 'intel', 'amd', 'cpu']
# If user specified a preference (not auto), try that first
if ENCODER_PREFERENCE != 'auto':
if ENCODER_PREFERENCE in ENCODER_CONFIGS:
print(f"Testing user-specified encoder: {ENCODER_PREFERENCE}")
if test_encoder(ENCODER_PREFERENCE):
encoder_type = ENCODER_PREFERENCE
config = ENCODER_CONFIGS[encoder_type]
print()
print("=" * 60)
print(f"Selected Encoder: {config['name']} ({config['codec']})")
print("=" * 60)
print()
return encoder_type
else:
print(f" User-specified encoder '{ENCODER_PREFERENCE}' is not available")
print(f" Falling back to auto-detection...")
print()
else:
print(f" Invalid encoder preference: '{ENCODER_PREFERENCE}'")
print(f" Valid options: auto, nvidia, intel, amd, cpu")
print(f" Falling back to auto-detection...")
print()
# Auto-detection: try each encoder in preference order
print("Auto-detecting available encoders...")
print()
for encoder_type in fallback_chain:
if test_encoder(encoder_type):
config = ENCODER_CONFIGS[encoder_type]
print()
print("=" * 60)
print(f"Selected Encoder: {config['name']} ({config['codec']})")
print("=" * 60)
print()
return encoder_type
# This should never happen since CPU always works, but just in case
print()
print("=" * 60)
print("WARNING: No encoders available! Defaulting to CPU")
print("=" * 60)
print()
return 'cpu'
# Detect encoder at startup
SELECTED_ENCODER = detect_encoder()
SELECTED_ENCODER_CONFIG = ENCODER_CONFIGS[SELECTED_ENCODER]
# ========== End Hardware Encoder Detection ==========
PROC = None
LOCK = threading.Lock()
LAST_HIT = 0.0
LAST_CLIENT_DISCONNECT = 0.0 # Track when last client disconnected
MODE = "idle" # "idle", "black", or "live"
CUR_IN1 = None
CUR_IN2 = None
CUR_AUDIO_MODE = 0 # Audio mode used for current stream (legacy)
# New layout system globals
CUR_LAYOUT = None # Current layout type
CUR_INPUTS = [] # List of input URLs in slot order
CUR_AUDIO_INDEX = 0 # Index of input providing audio
CUR_CUSTOM_SLOTS = None # For custom layouts, list of slot definitions
# Channel storage (in-memory)
CHANNELS = []
CHANNELS_LOCK = threading.Lock()
# Current layout configuration
CURRENT_LAYOUT = None
CURRENT_LAYOUT_LOCK = threading.Lock()
# Last layout configuration (persists through idle mode for cold start)
LAST_LAYOUT = None
LAST_LAYOUT_LOCK = threading.Lock()
# Broadcast system for streaming to multiple clients
BROADCAST_CLIENTS: Set[queue.Queue] = set()
BROADCAST_LOCK = threading.Lock()
# ========== Audio Volume Control with ZeroMQ ==========
class AudioVolumeController:
"""Manages dynamic audio volume control via ZeroMQ sockets."""
def __init__(self):
self.context = zmq.Context()
self.sockets = {} # stream_index → socket
self.lock = threading.Lock()
def create_socket(self, stream_index: int) -> str:
"""Create ZMQ socket for stream, return bind address."""
with self.lock:
# Clean up existing socket if any
if stream_index in self.sockets:
try:
self.sockets[stream_index].close()
except:
pass
socket = self.context.socket(zmq.REQ)
address = f"ipc:///tmp/zmq-stream-{stream_index}"
socket.connect(address)
socket.setsockopt(zmq.RCVTIMEO, 1000) # 1 second timeout
socket.setsockopt(zmq.SNDTIMEO, 1000)
self.sockets[stream_index] = socket
return address
def set_volume(self, stream_index: int, volume: float) -> bool:
"""Send volume command to FFmpeg via ZMQ. Returns True on success."""
with self.lock:
if stream_index not in self.sockets:
print(f"No ZMQ socket for stream {stream_index}")
return False
try:
# Send ZMQ command: "volume <value>"
command = f"volume {volume}"
self.sockets[stream_index].send_string(command)
# Wait for ACK
response = self.sockets[stream_index].recv_string()
print(f"Set volume for stream {stream_index} to {volume}: {response}")
return True
except zmq.error.Again:
print(f"ZMQ timeout setting volume for stream {stream_index}")
return False
except Exception as e:
print(f"Error setting volume for stream {stream_index}: {e}")
return False
def cleanup(self):
"""Close all sockets."""
with self.lock:
for socket in self.sockets.values():
try:
socket.close()
except:
pass
self.sockets.clear()
# Global audio controller
audio_controller = AudioVolumeController()
# ========== End Audio Volume Control ==========
# Pydantic models for API
class LayoutConfigModel(BaseModel):
layout: str # 'pip', 'split_h', 'grid_2x2', 'custom', etc.
streams: Dict[str, str] # slotId -> channelId
audio_source: str # slotId providing audio
custom_slots: list = None # For custom layouts: [{ id, name, x, y, width, height }]
audio_volumes: Dict[str, float] = None # slotId -> volume (0.0-1.0), optional
app.mount("/hls", StaticFiles(directory=OUTDIR), name="hls")
# Mount frontend static files if they exist (unified build)
STATIC_DIR = "/app/static"
if os.path.exists(STATIC_DIR):
# Serve _next static assets
next_static = os.path.join(STATIC_DIR, "_next")
if os.path.exists(next_static):
app.mount("/_next", StaticFiles(directory=next_static), name="next_static")
@app.middleware("http")
async def touch_last_hit(request: Request, call_next):
global LAST_HIT
if request.url.path.startswith("/hls") or request.url.path == "/stream":
LAST_HIT = time.time()
return await call_next(request)
# ========== M3U Parsing ==========
def parse_m3u(content: str):
"""
Parse M3U content and return list of channel dictionaries.
Expected format:
#EXTINF:-1 tvg-id="..." tvg-name="..." tvg-logo="..." tvg-chno="..." group-title="...",Display Name
http://stream.url
"""
channels = []
lines = content.strip().split('\n')
i = 0
while i < len(lines):
line = lines[i].strip()
# Look for #EXTINF lines
if line.startswith('#EXTINF:'):
# Extract metadata using regex
tvg_id = ""
tvg_name = ""
tvg_logo = ""
tvg_chno = ""
group_title = ""
display_name = ""
# Extract tvg-id
match = re.search(r'tvg-id="([^"]*)"', line)
if match:
tvg_id = match.group(1)
# Extract tvg-name
match = re.search(r'tvg-name="([^"]*)"', line)
if match:
tvg_name = match.group(1)
# Extract tvg-logo
match = re.search(r'tvg-logo="([^"]*)"', line)
if match:
tvg_logo = match.group(1)
# Extract tvg-chno
match = re.search(r'tvg-chno="([^"]*)"', line)
if match:
tvg_chno = match.group(1)
# Extract group-title
match = re.search(r'group-title="([^"]*)"', line)
if match:
group_title = match.group(1)
# Extract display name (after last comma)
if ',' in line:
display_name = line.split(',', 1)[1].strip()
# Next line should be the stream URL
i += 1
if i < len(lines):
stream_url = lines[i].strip()
# Skip empty URLs or comments
if stream_url and not stream_url.startswith('#'):
# Generate unique ID (use tvg-id if available, otherwise UUID)
channel_id = tvg_id if tvg_id else str(uuid.uuid4())
# Prefer tvg-name, fall back to display_name
name = tvg_name if tvg_name else display_name
if name == "MultiView":
continue
channels.append({
"id": channel_id,
"name": name,
"icon": tvg_logo,
"url": stream_url,
"group": group_title,
"channel_number": tvg_chno,
})
i += 1
return channels
def fetch_and_parse_m3u():
"""Fetch M3U from source and parse it."""
try:
# Check if M3U_SOURCE is a URL or file path
if M3U_SOURCE.startswith('http://') or M3U_SOURCE.startswith('https://'):
# Fetch from URL
with urlopen(M3U_SOURCE, timeout=30) as response:
content = response.read().decode('utf-8')
else:
# Read from file
with open(M3U_SOURCE, 'r', encoding='utf-8') as f:
content = f.read()
return parse_m3u(content)
except URLError as e:
print(f"Error fetching M3U from URL: {e}")
return []
except FileNotFoundError:
print(f"M3U file not found: {M3U_SOURCE}")
return []
except Exception as e:
print(f"Error parsing M3U: {e}")
return []
def load_channels():
"""Load channels from M3U source into global CHANNELS list."""
global CHANNELS
with CHANNELS_LOCK:
CHANNELS = fetch_and_parse_m3u()
print(f"Loaded {len(CHANNELS)} channels from M3U")
# ========== End M3U Parsing ==========
def _headers_value():
return SOURCE_HEADERS.replace("\\n", "\r\n") if SOURCE_HEADERS else ""
def _gpu_or_cpu_parts():
"""Return FFmpeg encoder arguments based on detected hardware encoder."""
return SELECTED_ENCODER_CONFIG['encode_args']
def _output_parts():
"""
Output MPEG-TS to stdout for broadcasting to multiple HTTP clients.
This mimics HDHomeRun behavior - each client starts at the live point.
"""
return [
"-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "2",
"-fflags", "+genpts",
"-flags", "low_delay",
"-f", "mpegts",
"-mpegts_copyts", "0",
"pipe:1" # Output to stdout
]
def build_black_cmd():
# Pure black video + silent audio; no text overlay (avoids drawtext dependency)
cmd = [
"ffmpeg","-loglevel","warning","-hide_banner","-nostdin",
"-re","-f","lavfi","-i","color=c=black:s=1920x1080:r=30",
"-f","lavfi","-i","anullsrc=channel_layout=stereo:sample_rate=48000",
"-map","0:v","-map","1:a",
]
cmd += _gpu_or_cpu_parts() + _output_parts()
return cmd
def build_live_cmd(in1: str, in2: str, audio_mode: int):
# Legacy function for backward compatibility - delegates to build_layout_cmd
return build_layout_cmd('pip', [in1, in2], audio_mode)
def build_audio_filter(num_streams: int, audio_volumes: dict = None) -> str:
"""
Build audio filter with volume controls for each stream.
Args:
num_streams: Number of audio streams
audio_volumes: Dict mapping stream index to volume (0.0-1.0). If None, all default to 1.0
Returns:
Audio filter_complex string
"""
if num_streams == 0:
return ""
if audio_volumes is None:
audio_volumes = {}
audio_parts = []
# Create volume filter for each audio stream
for i in range(num_streams):
volume = audio_volumes.get(i, 1.0)
# Format audio and apply volume
audio_filter = (
f"[{i}:a]"
f"aformat=sample_rates=48000:channel_layouts=stereo,"
f"volume={volume}"
f"[a{i}]"
)
audio_parts.append(audio_filter)
# Mix all audio streams if multiple, otherwise just use the single stream
if num_streams > 1:
inputs = ''.join(f"[a{i}]" for i in range(num_streams))
mix_filter = f"{inputs}amix=inputs={num_streams}:duration=longest:normalize=0[aout]"
audio_parts.append(mix_filter)
else:
# Single stream, just pass through
audio_parts.append("[a0]anull[aout]")
return ";".join(audio_parts)
def build_layout_cmd(layout: str, input_urls: list, audio_index: int, custom_slots: list = None, audio_volumes: dict = None):
"""
Build FFmpeg command for any layout type.
Args:
layout: Layout type ('pip', 'split_h', 'split_v', 'grid_2x2', 'multi_pip_2', 'multi_pip_3', 'multi_pip_4', 'custom')
input_urls: List of input stream URLs (in slot order)
audio_index: Index of input to use for audio (0-based) - DEPRECATED, kept for compatibility
custom_slots: For custom layouts, list of slot definitions with x, y, width, height
audio_volumes: Dict mapping stream index to volume (0.0-1.0)
"""
# Build video filter_complex based on layout
if layout == 'pip':
video_fc = build_pip_filter(input_urls)
elif layout == 'dvd_pip':
video_fc = build_dvd_pip_filter(input_urls)
elif layout == 'split_h':
video_fc = build_split_h_filter(input_urls)
elif layout == 'split_v':
video_fc = build_split_v_filter(input_urls)
elif layout == 'grid_2x2':
video_fc = build_grid_2x2_filter(input_urls)
elif layout == 'multi_pip_2':
video_fc = build_multi_pip_2_filter(input_urls)
elif layout == 'multi_pip_3':
video_fc = build_multi_pip_3_filter(input_urls)
elif layout == 'multi_pip_4':
video_fc = build_multi_pip_4_filter(input_urls)
elif layout == 'custom':
if not custom_slots:
raise ValueError("Custom layout requires slot definitions")
video_fc = build_custom_layout_filter(custom_slots)
else:
raise ValueError(f"Unknown layout type: {layout}")
# Build audio filter with ZeroMQ controls
audio_fc = build_audio_filter(len(input_urls), audio_volumes)
# Combine video and audio filters
fc = f"{video_fc};{audio_fc}"
# Map both video and audio outputs
amap = ["-map", "[v]", "-map", "[aout]"]
# Build ffmpeg command with all inputs
cmd = ["ffmpeg", "-loglevel", "warning", "-hide_banner", "-nostdin"]
# Add each input with reconnection options
for url in input_urls:
cmd += [
"-thread_queue_size", "1024", "-user_agent", DEFAULT_UA,
]
if SOURCE_HEADERS.strip():
cmd += ["-headers", _headers_value()]
cmd += [
"-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_on_network_error", "1",
"-rw_timeout", "15000000", "-timeout", "15000000",
"-i", url,
]
# Add filter_complex and audio mapping
cmd += ["-filter_complex", fc]
cmd += amap + _gpu_or_cpu_parts() + _output_parts()
return cmd
def build_pip_filter(inputs: list) -> str:
"""Picture-in-Picture: 1 main + 1 inset"""
return (
"[0:v]fps=30,scale=1920:-2:force_original_aspect_ratio=decrease,"
"pad=1920:1080:(ow-iw)/2:(oh-ih)/2,setsar=1[base];"
f"[1:v]scale={INSET_SCALE}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={INSET_SCALE+16}:376:8:8:color=white[pip];"
f"[base][pip]overlay=W-w-{INSET_MARGIN}:H-h-{INSET_MARGIN}:shortest=1[v]"
)
def build_dvd_pip_filter(inputs: list) -> str:
"""DVD Screensaver PiP: 1 main + 1 bouncing inset (just like the DVD logo!)"""
margin = 10
# Triangle wave expressions for smooth bouncing
# x bounces horizontally at 100 pixels/second
# y bounces vertically at 75 pixels/second (different speed for diagonal effect)
x_expr = f"abs(mod(t*100, 2*(W-w-{margin})) - (W-w-{margin}))"
y_expr = f"abs(mod(t*75, 2*(H-h-{margin})) - (H-h-{margin}))"
return (
"[0:v]fps=30,scale=1920:-2:force_original_aspect_ratio=decrease,"
"pad=1920:1080:(ow-iw)/2:(oh-ih)/2,setsar=1[base];"
f"[1:v]scale={INSET_SCALE}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={INSET_SCALE+16}:376:8:8:color=white[pip];"
f"[base][pip]overlay=x='{x_expr}':y='{y_expr}':shortest=1[v]"
)
def build_split_h_filter(inputs: list) -> str:
"""Split Horizontal: 2 streams side-by-side"""
return (
"[0:v]fps=30,scale=960:-2:force_original_aspect_ratio=decrease,"
"pad=960:1080:(ow-iw)/2:(oh-ih)/2,setsar=1[left];"
"[1:v]fps=30,scale=960:-2:force_original_aspect_ratio=decrease,"
"pad=960:1080:(ow-iw)/2:(oh-ih)/2,setsar=1[right];"
"[left][right]hstack=inputs=2:shortest=0[v]"
)
def build_split_v_filter(inputs: list) -> str:
"""Split Vertical: 2 streams stacked"""
return (
"[0:v]fps=30,scale=1920:540:force_original_aspect_ratio=decrease,"
"pad=1920:540:(ow-iw)/2:(oh-ih)/2,setsar=1[top];"
"[1:v]fps=30,scale=1920:540:force_original_aspect_ratio=decrease,"
"pad=1920:540:(ow-iw)/2:(oh-ih)/2,setsar=1[bottom];"
"[top][bottom]vstack=inputs=2:shortest=0[v]"
)
def build_grid_2x2_filter(inputs: list) -> str:
"""2x2 Grid: 4 equal streams"""
return (
"[0:v]fps=30,scale=960:540:force_original_aspect_ratio=decrease,"
"pad=960:540:(ow-iw)/2:(oh-ih)/2,setsar=1[s0];"
"[1:v]fps=30,scale=960:540:force_original_aspect_ratio=decrease,"
"pad=960:540:(ow-iw)/2:(oh-ih)/2,setsar=1[s1];"
"[2:v]fps=30,scale=960:540:force_original_aspect_ratio=decrease,"
"pad=960:540:(ow-iw)/2:(oh-ih)/2,setsar=1[s2];"
"[3:v]fps=30,scale=960:540:force_original_aspect_ratio=decrease,"
"pad=960:540:(ow-iw)/2:(oh-ih)/2,setsar=1[s3];"
"[s0][s1]hstack=inputs=2:shortest=0[top];"
"[s2][s3]hstack=inputs=2:shortest=0[bottom];"
"[top][bottom]vstack=inputs=2:shortest=0[v]"
)
def build_multi_pip_2_filter(inputs: list) -> str:
"""Multi-PiP (2): 1 main + 2 small insets"""
inset_w = 480
inset_h = 270
margin = 20
return (
"[0:v]fps=30,scale=1920:-2:force_original_aspect_ratio=decrease,"
"pad=1920:1080:(ow-iw)/2:(oh-ih)/2,setsar=1[base];"
f"[1:v]fps=30,scale={inset_w}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={inset_w+8}:{inset_h+8}:4:4:color=white[pip1];"
f"[2:v]fps=30,scale={inset_w}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={inset_w+8}:{inset_h+8}:4:4:color=white[pip2];"
f"[base][pip1]overlay=W-w-{margin}:H-h-{margin}:shortest=0[tmp];"
f"[tmp][pip2]overlay=W-w-{margin}:H-h-{margin}-{inset_h+8+10}:shortest=0[v]"
)
def build_multi_pip_3_filter(inputs: list) -> str:
"""Multi-PiP (3): 1 main + 3 small insets"""
inset_w = 384
inset_h = 216
margin = 20
gap = 10
return (
"[0:v]fps=30,scale=1920:-2:force_original_aspect_ratio=decrease,"
"pad=1920:1080:(ow-iw)/2:(oh-ih)/2,setsar=1[base];"
f"[1:v]fps=30,scale={inset_w}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={inset_w+8}:{inset_h+8}:4:4:color=white[pip1];"
f"[2:v]fps=30,scale={inset_w}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={inset_w+8}:{inset_h+8}:4:4:color=white[pip2];"
f"[3:v]fps=30,scale={inset_w}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={inset_w+8}:{inset_h+8}:4:4:color=white[pip3];"
f"[base][pip1]overlay=W-w-{margin}:H-h-{margin}:shortest=0[tmp1];"
f"[tmp1][pip2]overlay=W-w-{margin}:H-h-{margin}-{inset_h+8+gap}:shortest=0[tmp2];"
f"[tmp2][pip3]overlay=W-w-{margin}:H-h-{margin}-2*({inset_h+8+gap}):shortest=0[v]"
)
def build_multi_pip_4_filter(inputs: list) -> str:
"""Multi-PiP (4): 1 main + 4 small insets"""
inset_w = 384
inset_h = 216
margin = 20
gap = 10
return (
"[0:v]fps=30,scale=1920:-2:force_original_aspect_ratio=decrease,"
"pad=1920:1080:(ow-iw)/2:(oh-ih)/2,setsar=1[base];"
f"[1:v]fps=30,scale={inset_w}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={inset_w+8}:{inset_h+8}:4:4:color=white[pip1];"
f"[2:v]fps=30,scale={inset_w}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={inset_w+8}:{inset_h+8}:4:4:color=white[pip2];"
f"[3:v]fps=30,scale={inset_w}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={inset_w+8}:{inset_h+8}:4:4:color=white[pip3];"
f"[4:v]fps=30,scale={inset_w}:-2:force_original_aspect_ratio=decrease,setsar=1,"
f"pad={inset_w+8}:{inset_h+8}:4:4:color=white[pip4];"
f"[base][pip1]overlay=W-w-{margin}:H-h-{margin}:shortest=0[tmp1];"
f"[tmp1][pip2]overlay=W-w-{margin}:H-h-{margin}-{inset_h+8+gap}:shortest=0[tmp2];"
f"[tmp2][pip3]overlay=W-w-{margin}:{margin}:shortest=0[tmp3];"
f"[tmp3][pip4]overlay=W-w-{margin}:{margin}+{inset_h+8+gap}:shortest=0[v]"
)
def build_custom_layout_filter(slots: list) -> str:
"""
Custom Layout: User-defined slot positions and sizes.
Args:
slots: List of dicts with keys: x, y, width, height, border (all in pixels, border is boolean)
Returns:
FFmpeg filter_complex string
"""
if not slots or len(slots) > 5:
raise ValueError("Custom layout must have 1-5 slots")
# Sort slots by size (largest first) for z-ordering
sorted_slots = sorted(slots, key=lambda s: s['width'] * s['height'], reverse=True)
# Build filter string
parts = []
# Scale each input to its slot dimensions
for i, slot in enumerate(sorted_slots):
w = slot['width']
h = slot['height']
has_border = slot.get('border', False)
# Base scale and pad to ensure content fits
filter_chain = f"[{i}:v]fps=30,scale={w}:{h}:force_original_aspect_ratio=decrease," \
f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2,setsar=1"
# Add white border if enabled (8px on all sides)
if has_border:
border_width = w + 16 # 8px on each side
border_height = h + 16
filter_chain += f",pad={border_width}:{border_height}:8:8:color=white"
filter_chain += f"[s{i}]"
parts.append(filter_chain)
# Create black 1920x1080 base
parts.append("color=c=black:s=1920x1080:r=30[base]")
# Chain overlays
prev_label = "base"
for i, slot in enumerate(sorted_slots):
x = slot['x']
y = slot['y']
has_border = slot.get('border', False)
# Adjust position if border is enabled (offset by -8px to account for border)
if has_border:
x = max(0, x - 8)
y = max(0, y - 8)
if i == len(sorted_slots) - 1:
# Last overlay outputs to [v]
parts.append(f"[{prev_label}][s{i}]overlay={x}:{y}:shortest=0[v]")
else:
# Intermediate overlays
parts.append(f"[{prev_label}][s{i}]overlay={x}:{y}:shortest=0[tmp{i}]")
prev_label = f"tmp{i}"
return ";".join(parts)
def stop_ffmpeg():
global PROC
if PROC and PROC.poll() is None:
try:
PROC.send_signal(signal.SIGINT)
PROC.wait(timeout=3)
except Exception:
try: PROC.kill()
except Exception: pass
PROC = None
def clean_outdir():
"""Clean output directory completely."""
for p in pathlib.Path(OUTDIR).glob("*"):
try: p.unlink()
except: pass
def stop_to_idle():
"""Stop FFmpeg completely and enter idle mode (zero GPU usage)."""
global PROC, MODE, CUR_IN1, CUR_IN2, CUR_AUDIO_MODE, LAST_HIT, CUR_LAYOUT, CUR_INPUTS, CUR_AUDIO_INDEX, CUR_CUSTOM_SLOTS, CURRENT_LAYOUT, LAST_LAYOUT
# Save current layout to LAST_LAYOUT before clearing (for cold start)
with CURRENT_LAYOUT_LOCK:
if CURRENT_LAYOUT:
with LAST_LAYOUT_LOCK:
LAST_LAYOUT = CURRENT_LAYOUT.copy()
print(f"Saved layout '{LAST_LAYOUT.get('layout')}' for cold start")
with LOCK:
stop_ffmpeg()
clean_outdir()
MODE = "idle"
# Don't clear layout globals - keep them for cold start via LAST_LAYOUT
# CUR_LAYOUT, CUR_INPUTS, etc. stay populated for restart_last_layout()
# Legacy vars cleared
CUR_IN1 = CUR_IN2 = None
CUR_AUDIO_MODE = 0
LAST_HIT = time.time()
# Clear current layout state (but LAST_LAYOUT persists)
with CURRENT_LAYOUT_LOCK:
CURRENT_LAYOUT = None
print(f"Entered idle mode (no FFmpeg process, layout saved for cold start)")
def start_black():
"""Legacy black screen mode - kept for compatibility."""
global PROC, LAST_HIT, MODE, CUR_IN1, CUR_IN2, CUR_AUDIO_MODE, CUR_LAYOUT, CUR_INPUTS, CUR_AUDIO_INDEX, CUR_CUSTOM_SLOTS, CURRENT_LAYOUT
with LOCK:
stop_ffmpeg()
clean_outdir()
# Capture stdout for broadcasting to HTTP clients
PROC = subprocess.Popen(
build_black_cmd(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0
)
MODE = "black"
CUR_IN1 = CUR_IN2 = None
CUR_AUDIO_MODE = 0
CUR_LAYOUT = None
CUR_INPUTS = []
CUR_AUDIO_INDEX = 0
CUR_CUSTOM_SLOTS = None
LAST_HIT = time.time()
# Clear current layout when stopping
with CURRENT_LAYOUT_LOCK:
CURRENT_LAYOUT = None
def start_live(in1: str, in2: str):
global PROC, LAST_HIT, MODE, CUR_IN1, CUR_IN2
with LOCK:
stop_ffmpeg()
clean_outdir()
# Capture stdout for broadcasting to HTTP clients
PROC = subprocess.Popen(
build_live_cmd(in1, in2, AUDIO_SOURCE),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0
)
MODE = "live"
CUR_IN1, CUR_IN2 = in1, in2
LAST_HIT = time.time()
def get_expected_slots_for_layout(layout: str) -> list:
"""Return the expected slot IDs for a given layout type."""
LAYOUT_SLOTS = {
'pip': ['main', 'inset'],
'dvd_pip': ['main', 'inset'],
'split_h': ['left', 'right'],
'split_v': ['top', 'bottom'],
'grid_2x2': ['slot1', 'slot2', 'slot3', 'slot4'],
'multi_pip_2': ['main', 'inset1', 'inset2'],
'multi_pip_3': ['main', 'inset1', 'inset2', 'inset3'],
'multi_pip_4': ['main', 'inset1', 'inset2', 'inset3', 'inset4'],
}
return LAYOUT_SLOTS.get(layout, [])
def ensure_running():
"""Legacy: ensure FFmpeg is running - now starts in idle mode instead."""
# No longer auto-starts black screen
# Streams start on-demand when /stream is accessed
pass
def restart_last_layout():
"""Restart FFmpeg with the last known layout configuration."""
global PROC, MODE, LAST_HIT, CUR_LAYOUT, CUR_INPUTS, CUR_AUDIO_INDEX, CUR_IN1, CUR_IN2, CUR_AUDIO_MODE, CUR_CUSTOM_SLOTS
if not CUR_LAYOUT or not CUR_INPUTS:
print("Cannot restart: no layout configured")
return False
# Get audio_volumes from current layout
with CURRENT_LAYOUT_LOCK:
audio_volumes = CURRENT_LAYOUT.get("audio_volumes", {}) if CURRENT_LAYOUT else {}
# Convert slot-based volumes to index-based volumes
audio_volumes_by_index = {}
if audio_volumes and CURRENT_LAYOUT:
# Get expected slots - handle custom layouts
if CUR_LAYOUT == 'custom' and CUR_CUSTOM_SLOTS:
sorted_slots = sorted(CUR_CUSTOM_SLOTS, key=lambda s: s['width'] * s['height'], reverse=True)
expected_slots = [slot['id'] for slot in sorted_slots]
else:
expected_slots = get_expected_slots_for_layout(CUR_LAYOUT)
for slot_id, channel_id in CURRENT_LAYOUT.get("streams", {}).items():
if slot_id in audio_volumes and slot_id in expected_slots:
index = expected_slots.index(slot_id)
audio_volumes_by_index[index] = audio_volumes[slot_id]
try:
with LOCK:
stop_ffmpeg()
clean_outdir()
PROC = subprocess.Popen(
build_layout_cmd(CUR_LAYOUT, CUR_INPUTS, CUR_AUDIO_INDEX, CUR_CUSTOM_SLOTS, audio_volumes_by_index),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0
)
MODE = "live"
# Update legacy vars for backward compatibility
if len(CUR_INPUTS) >= 2:
CUR_IN1, CUR_IN2 = CUR_INPUTS[0], CUR_INPUTS[1]
CUR_AUDIO_MODE = CUR_AUDIO_INDEX if CUR_AUDIO_INDEX in [0, 1] else 0
LAST_HIT = time.time()
print(f"Restarted layout '{CUR_LAYOUT}' with {len(CUR_INPUTS)} streams")
return True
except Exception as e:
print(f"Failed to restart layout: {e}")
return False
def restart_current_stream():
"""Restart FFmpeg with the same settings to prevent file size growth."""
global MODE, CUR_IN1, CUR_IN2, CUR_AUDIO_MODE, CUR_LAYOUT, CUR_INPUTS, CUR_AUDIO_INDEX, CUR_CUSTOM_SLOTS, PROC, LAST_HIT
if MODE == "black":
start_black()
elif MODE == "live":
# Use new layout system if available, otherwise fall back to legacy
if CUR_LAYOUT and CUR_INPUTS:
# Get audio_volumes from current layout
with CURRENT_LAYOUT_LOCK:
audio_volumes = CURRENT_LAYOUT.get("audio_volumes", {}) if CURRENT_LAYOUT else {}
# Convert slot-based volumes to index-based volumes
audio_volumes_by_index = {}
if audio_volumes and CURRENT_LAYOUT:
# Get expected slots - handle custom layouts
if CUR_LAYOUT == 'custom' and CUR_CUSTOM_SLOTS:
sorted_slots = sorted(CUR_CUSTOM_SLOTS, key=lambda s: s['width'] * s['height'], reverse=True)
expected_slots = [slot['id'] for slot in sorted_slots]
else:
expected_slots = get_expected_slots_for_layout(CUR_LAYOUT)
for slot_id, channel_id in CURRENT_LAYOUT.get("streams", {}).items():
if slot_id in audio_volumes and slot_id in expected_slots:
index = expected_slots.index(slot_id)
audio_volumes_by_index[index] = audio_volumes[slot_id]
with LOCK:
stop_ffmpeg()
clean_outdir()
PROC = subprocess.Popen(
build_layout_cmd(CUR_LAYOUT, CUR_INPUTS, CUR_AUDIO_INDEX, CUR_CUSTOM_SLOTS, audio_volumes_by_index),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0
)
MODE = "live"
LAST_HIT = time.time()
elif CUR_IN1 and CUR_IN2:
# Legacy restart
with LOCK:
stop_ffmpeg()
clean_outdir()
PROC = subprocess.Popen(
build_live_cmd(CUR_IN1, CUR_IN2, CUR_AUDIO_MODE),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0
)
MODE = "live"
LAST_HIT = time.time()
def idle_watchdog():
global MODE, LAST_CLIENT_DISCONNECT
while True:
time.sleep(5)
# Get current client count
with BROADCAST_LOCK:
client_count = len(BROADCAST_CLIENTS)
# Track when last client disconnected
if client_count == 0 and MODE == "live":
if LAST_CLIENT_DISCONNECT == 0:
LAST_CLIENT_DISCONNECT = time.time()
elif time.time() - LAST_CLIENT_DISCONNECT > IDLE_TIMEOUT:
print(f"No clients for {IDLE_TIMEOUT}s, entering idle mode")