-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1715 lines (1492 loc) · 66.5 KB
/
main.py
File metadata and controls
1715 lines (1492 loc) · 66.5 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 base64
import hashlib
import hmac
import json
import logging
import os
import platform as _platform
import re
import secrets
import shlex
import shutil
import signal
import subprocess
import sys
import time
import uuid
from contextlib import asynccontextmanager
from datetime import datetime
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
from fastapi import FastAPI, File, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
# ── Logging ───────────────────────────────────────────────────────────────────
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("streamrec")
# ── Platform detection ────────────────────────────────────────────────────────
IS_WINDOWS = _platform.system() == "Windows"
PI_MODE = os.environ.get("STREAMREC_PI_MODE", "0") == "1"
# ── Paths ─────────────────────────────────────────────────────────────────────
# Docker sets RECORDINGS_DIR=/recordings | bare metal falls back to ~/StreamRec/recordings
_rec_env = os.environ.get("RECORDINGS_DIR", "")
if _rec_env:
RECORDINGS_DIR = Path(_rec_env)
else:
RECORDINGS_DIR = Path.home() / "StreamRec" / "recordings"
RECORDINGS_DIR.mkdir(parents=True, exist_ok=True)
STATE_FILE = RECORDINGS_DIR / "state.json"
COOKIES_DIR = RECORDINGS_DIR / "cookies"
COOKIES_DIR.mkdir(exist_ok=True)
ACCOUNT_FILE = RECORDINGS_DIR / "account.json"
AVATAR_DIR = RECORDINGS_DIR / "avatars"
AVATAR_DIR.mkdir(exist_ok=True)
# Static files: Docker puts index.html in /app, bare metal uses same dir as main.py
_static_dir = os.environ.get("STATIC_DIR", str(Path(__file__).parent))
# ── Version ───────────────────────────────────────────────────────────────────
VERSION = "1.0.0"
# ── App ───────────────────────────────────────────────────────────────────────
@asynccontextmanager
async def lifespan(app: FastAPI):
_load_state()
logger.info("StreamRec %s starting — %d channels loaded", VERSION, len(channels))
task = asyncio.create_task(_supervised_monitor())
yield
task.cancel()
try:
await asyncio.wait_for(task, timeout=5)
except (asyncio.CancelledError, asyncio.TimeoutError):
pass
# Drain any active recordings so we don't leave zombie yt-dlp children behind
for rec in list(recordings.values()):
if rec.get("status") in ("recording", "starting") and rec.get("pid"):
_stop_rec(rec, force=False)
_save_state_sync()
logger.info("StreamRec shutting down")
async def _supervised_monitor():
"""Keep the monitor loop alive even if a single tick raises unexpectedly."""
while True:
try:
await monitor_loop()
except asyncio.CancelledError:
raise
except Exception as e:
logger.exception("monitor_loop crashed: %s — restarting in 10s", e)
await asyncio.sleep(10)
app = FastAPI(title="StreamRec API", version=VERSION, lifespan=lifespan)
_proc_semaphore = asyncio.Semaphore(3 if PI_MODE else 6)
channels: dict[str, dict] = {}
recordings: dict[str, dict] = {}
_disk_cache: dict = {}
_disk_cache_ts: float = 0
# ── Tuning helpers (Pi vs. normal) ───────────────────────────────────────────
# These read from `settings["pi_mode"]` at call time so the toggle takes
# effect immediately without a restart.
def _is_pi() -> bool:
"""True when Potato / Pi mode is active (env var OR settings toggle)."""
return settings.get("pi_mode", PI_MODE)
def get_size_poll_interval() -> int:
return 8 if _is_pi() else 3
def get_log_limits() -> tuple[int, int]:
"""Return (max_lines, trim_to) for the recording log buffer."""
return (60, 30) if _is_pi() else (100, 50)
def get_frontend_poll_hint() -> int:
return 10 if _is_pi() else 5
def get_disk_cache_ttl() -> int:
return 60 if _is_pi() else 30
def get_ffmpeg_threads() -> str:
return "1" if _is_pi() else "2"
# Streaming / preview constants — large chunks reduce HTTP round-trips and
# I/O syscalls, critical on Raspberry Pi / slow SD cards.
PREVIEW_RANGE_CHUNK = 10 * 1024 * 1024 # 10 MB per HTTP range response
PREVIEW_READ_CHUNK = 512 * 1024 # 512 KB per file read()
# Remux timeout — 5 min to handle large files on slow Pi SD cards
REMUX_TIMEOUT = 300
# ── Debounced state persistence ──────────────────────────────────────────────
_save_state_pending = False
_save_state_task: Optional[asyncio.Task] = None
def _schedule_save_state():
"""Debounce state saves — collapse rapid writes into one disk write."""
global _save_state_pending, _save_state_task
_save_state_pending = True
if _save_state_task and not _save_state_task.done():
return # already scheduled
_save_state_task = asyncio.get_running_loop().create_task(_debounced_save())
async def _debounced_save():
"""Wait for writes to settle, then flush once."""
global _save_state_pending
while True:
_save_state_pending = False
await asyncio.sleep(2) # coalesce window
if not _save_state_pending:
break # no new writes arrived — safe to flush
_save_state_sync()
settings: dict = {
"pi_mode": PI_MODE,
"monitor_interval": 120 if PI_MODE else 60,
"default_quality": "best",
"default_format": "mp4",
"auto_convert_mp4": False,
"delete_original": False,
"record_on_add": False,
"auto_retry": True,
"max_retries": 5,
"retry_delay": 15,
"proxy": "",
"cookies_file": "",
"extra_args": "",
}
# ── Cross-platform process helpers ────────────────────────────────────────────
def _subprocess_kwargs() -> dict:
"""
Extra kwargs for asyncio.create_subprocess_exec so we can kill the whole
process tree later.
- Windows: CREATE_NEW_PROCESS_GROUP lets us send CTRL_BREAK_EVENT to the group.
- Unix: setsid creates a new session; killpg kills the whole group.
"""
if IS_WINDOWS:
return {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
return {"preexec_fn": os.setsid}
def _kill_proc(pid: int, force: bool = False) -> None:
"""Terminate or kill a process (and its children) cross-platform."""
try:
if IS_WINDOWS:
# CTRL_BREAK_EVENT propagates to the whole process group on Windows
sig = signal.CTRL_BREAK_EVENT
os.kill(pid, sig)
if force:
# Give it a moment then hard-kill
import ctypes
ctypes.windll.kernel32.TerminateProcess(
ctypes.windll.kernel32.OpenProcess(1, False, pid), 1
)
else:
sig = signal.SIGKILL if force else signal.SIGTERM
try:
os.killpg(os.getpgid(pid), sig)
except (ProcessLookupError, PermissionError, OSError):
os.kill(pid, sig)
except (ProcessLookupError, PermissionError, OSError, AttributeError):
pass
# ── State persistence ─────────────────────────────────────────────────────────
def _save_state_sync():
"""Write state to disk immediately (internal — prefer _save_state)."""
saved_channels = {}
for cid, ch in channels.items():
c = dict(ch)
for k in ("recording_id", "is_live", "last_checked"):
c.pop(k, None)
saved_channels[cid] = c
# Persist finished recordings (completed/error) so they survive restarts
saved_recordings = {}
for rid, rec in recordings.items():
if rec.get("status") in ("completed", "error"):
saved_recordings[rid] = rec
try:
tmp = STATE_FILE.with_suffix(".tmp")
tmp.write_text(
json.dumps({
"channels": saved_channels,
"settings": settings,
"recordings": saved_recordings,
}, indent=2),
encoding="utf-8",
)
tmp.replace(STATE_FILE)
except Exception as e:
logger.warning("Failed to save state: %s", e)
def _save_state():
"""Save state — debounced in async context, immediate otherwise."""
try:
asyncio.get_running_loop() # check if we're in an async context
_schedule_save_state()
except RuntimeError:
# No running event loop (startup / sync context) — write immediately
_save_state_sync()
def _load_state():
global settings
if not STATE_FILE.exists():
return
try:
data = json.loads(STATE_FILE.read_text(encoding="utf-8"))
for cid, ch in data.get("channels", {}).items():
ch["recording_id"] = None
ch["is_live"] = False
ch["last_checked"] = None
# Re-detect platform for any channels saved as Unknown
if ch.get("platform") in ("Unknown", "", None) and ch.get("url"):
ch["platform"] = detect_platform(ch["url"])
# Fill display_name from URL if blank
if not ch.get("display_name") and ch.get("url"):
ch["display_name"] = _username_from_url(ch["url"])
if not ch.get("username") and ch.get("url"):
ch["username"] = _username_from_url(ch["url"])
channels[cid] = ch
for k, v in data.get("settings", {}).items():
if k in settings:
settings[k] = v
for rid, rec in data.get("recordings", {}).items():
# Strip any in-progress state fields that no longer apply
rec.pop("pid", None)
rec.pop("stopping", None)
rec.pop("speed", None)
recordings[rid] = rec
except Exception as e:
logger.warning("Failed to load state: %s", e)
# ── Platform detection ────────────────────────────────────────────────────────
PLATFORM_MAP = [
(r"youtube\.com|youtu\.be", "YouTube"),
(r"twitch\.tv", "Twitch"),
(r"tiktok\.com", "TikTok"),
(r"kick\.com", "Kick"),
(r"bilibili\.com", "Bilibili"),
(r"douyin\.com", "Douyin"),
(r"afreecatv\.com", "Afreeca"),
(r"sooplive\.co", "Sooplive"),
(r"naver\.com", "Naver"),
(r"weibo\.com", "Weibo"),
(r"huya\.com", "Huya"),
(r"douyu\.com", "Douyu"),
(r"nicovideo\.jp", "Niconico"),
(r"dailymotion\.com", "Dailymotion"),
(r"facebook\.com|fb\.watch", "Facebook"),
(r"instagram\.com", "Instagram"),
(r"twitter\.com|x\.com", "Twitter/X"),
(r"vimeo\.com", "Vimeo"),
(r"rumble\.com", "Rumble"),
(r"stripchat\.com", "Stripchat"),
(r"twitcasting\.tv", "Twitcasting"),
(r"pandalive\.co", "Pandalive"),
(r"bigo\.tv", "Bigo"),
(r"chaturbate\.com", "Chaturbate"),
(r"cam4\.com", "Cam4"),
(r"myfreecams\.com", "MyFreeCams"),
(r"camsoda\.com", "CamSoda"),
(r"bongacams\.com", "BongaCams"),
(r"cammodels\.com", "CamModels"),
(r"streamate\.com", "Streamate"),
(r"flirt4free\.com", "Flirt4Free"),
]
def detect_platform(url: str) -> str:
for pattern, name in PLATFORM_MAP:
if re.search(pattern, url, re.I):
return name
return "Unknown"
# ── Metadata fetch ────────────────────────────────────────────────────────────
def _username_from_url(url: str) -> str:
"""Best-effort username extraction directly from the URL path."""
try:
path = urlparse(url).path.strip("/")
# Take first non-empty path segment
part = path.split("/")[0] if path else ""
# Ignore generic segments
if part and part not in ("live", "channel", "watch", "user", "c", "videos"):
return part
except Exception:
pass
return ""
async def fetch_metadata(url: str) -> dict:
# Always extract a fallback username from the URL itself
url_username = _username_from_url(url)
try:
async with _proc_semaphore:
proc = await asyncio.create_subprocess_exec(
"yt-dlp", "--dump-single-json", "--no-download",
"--playlist-items", "1", "--socket-timeout", "15", url,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=30)
# Even if yt-dlp returns non-zero (offline room), stdout may still have data
if stdout:
try:
data = json.loads(stdout)
except Exception:
data = {}
else:
data = {}
thumbnails = data.get("thumbnails") or []
thumbnail = data.get("thumbnail") or (thumbnails[-1]["url"] if thumbnails else "")
avatar = ""
for t in reversed(thumbnails):
tid = (t.get("id") or "").lower()
if "avatar" in tid or "profile" in tid:
avatar = t.get("url", "")
break
if not avatar:
avatar = await _try_scrape_avatar(url)
# Prefer yt-dlp data, fall back to URL-parsed username
yt_name = data.get("uploader") or data.get("channel") or data.get("creator") or ""
yt_user = data.get("uploader_id") or data.get("channel_id") or ""
display_name = yt_name or url_username
username = yt_user or url_username
return {
"display_name": display_name,
"username": username,
"avatar": avatar,
"thumbnail": thumbnail,
"is_live": bool(data.get("is_live")),
}
except Exception:
# Total failure — still return URL-derived name so card isn't blank
if url_username:
return {
"display_name": url_username,
"username": url_username,
"avatar": "",
"thumbnail": "",
"is_live": False,
}
return {}
async def _try_scrape_avatar(url: str) -> str:
try:
async with _proc_semaphore:
proc = await asyncio.create_subprocess_exec(
"curl", "-sL", "--max-time", "10", "-A",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
url,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=15)
if not stdout:
return ""
html = stdout.decode("utf-8", errors="replace")
for pat in (r'"avatarLarger"\s*:\s*"([^"]+)"',
r'"avatarMedium"\s*:\s*"([^"]+)"',
r'"avatarThumb"\s*:\s*"([^"]+)"'):
m = re.search(pat, html)
if m:
return m.group(1).replace(r'\u002F', '/')
m = re.search(
r'<meta[^>]+property=["\']og:image["\'][^>]+content=["\']([^"\'>]+)["\']',
html, re.I,
)
if m:
return m.group(1)
except Exception:
pass
return ""
async def _check_chaturbate_live(url: str, proxy: str = "") -> Optional[bool]:
"""Scrape Chaturbate page directly — returns True/False/None (None = inconclusive)."""
try:
curl_cmd = [
"curl", "-sL", "--max-time", "10", "-A",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
" (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
]
if proxy:
curl_cmd += ["--proxy", proxy]
curl_cmd.append(url)
proc = await asyncio.create_subprocess_exec(
*curl_cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=15)
if not stdout:
return None
html = stdout.decode("utf-8", errors="replace")
# Chaturbate embeds room status in the page
if '"room_status": "public"' in html or '"room_status":"public"' in html:
return True
if 'offline' in html.lower() and 'room_status' in html:
return False
return None
except Exception:
return None
async def check_is_live(url: str, proxy: str = "") -> bool:
# For Chaturbate, try a fast HTTP scrape first before invoking yt-dlp
if re.search(r"chaturbate\.com", url, re.I):
result = await _check_chaturbate_live(url, proxy=proxy)
if result is not None:
return result
cmd = ["yt-dlp", "--simulate", "--no-warnings",
"--socket-timeout", "20", "--playlist-items", "1"]
if proxy:
cmd += ["--proxy", proxy]
cmd.append(url)
proc = None
try:
# Hold the semaphore across the full wait so the process cap is real.
async with _proc_semaphore:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
try:
await asyncio.wait_for(proc.wait(), timeout=35)
except asyncio.TimeoutError:
_kill_proc(proc.pid, force=True)
try:
await asyncio.wait_for(proc.wait(), timeout=2)
except asyncio.TimeoutError:
pass
return False
return proc.returncode == 0
except Exception as e:
logger.debug("check_is_live error for %s: %s", url, e)
if proc and proc.returncode is None:
try:
_kill_proc(proc.pid, force=True)
except Exception:
pass
return False
# ── Recording ─────────────────────────────────────────────────────────────────
async def _start_recording_for_channel(ch_id: str) -> Optional[str]:
ch = channels.get(ch_id)
if not ch:
return None
existing = ch.get("recording_id")
if existing and existing in recordings and recordings[existing]["status"] in ("recording", "starting"):
return None
rec_id = str(uuid.uuid4())[:8]
recordings[rec_id] = {
"id": rec_id, "channel_id": ch_id,
"url": ch["url"], "platform": ch["platform"],
"quality": ch.get("quality") or settings["default_quality"],
"format": ch.get("format") or settings["default_format"],
"status": "starting", "created_at": time.time(),
"started_at": None, "ended_at": None,
"bytes": 0, "speed": None,
"filepath": None, "filename": None,
"log": [], "stopping": False, "auto": False,
}
channels[ch_id]["recording_id"] = rec_id
asyncio.create_task(run_recording(rec_id))
return rec_id
async def run_recording(rec_id: str):
rec = recordings[rec_id]
ch = channels.get(rec["channel_id"], {})
quality = rec.get("quality") or settings["default_quality"]
fmt = rec.get("format") or settings["default_format"]
url = rec["url"]
platform_raw = rec.get("platform") or "Unknown"
platform = platform_raw.lower()
username = ch.get("display_name") or ch.get("username") or rec_id
safe_plat = re.sub(r'[^\w\-]', '_', platform_raw)
safe_user = re.sub(r'[^\w\-]', '_', username)
now = datetime.now()
date_str = now.strftime("%Y-%m-%d")
time_str = now.strftime("%H-%M-%S")
rec_dir = RECORDINGS_DIR / safe_plat / safe_user / date_str
rec_dir.mkdir(parents=True, exist_ok=True)
stem = f"{safe_user}_{date_str}_{time_str}"
output_path = rec_dir / f"{stem}.%(ext)s"
_no_live_from_start = (
"tiktok", "kick", "stripchat", "bigo", "pandalive",
"chaturbate", "cam4", "myfreecams", "camsoda", "bongacams",
"cammodels", "streamate", "flirt4free",
)
_cam_platforms = _no_live_from_start # same set for format logic
# Cam/HLS sites use numeric format IDs — "best" keyword alone fails.
# Build a fallback chain that works for both cam sites and regular streams.
_height_re = re.match(r'^(\d+)p?$', quality)
if quality in ("best", ""):
if platform in _cam_platforms:
effective_quality = "bestvideo+bestaudio/best"
else:
effective_quality = "bestvideo+bestaudio/bestvideo/best"
elif quality == "bestvideo+bestaudio":
effective_quality = "bestvideo+bestaudio/best"
elif _height_re and platform in _cam_platforms:
# e.g. "720p" or "720" on cam sites — use height filter with fallback
h = _height_re.group(1)
effective_quality = f"bestvideo[height<={h}]+bestaudio/best[height<={h}]/bestvideo+bestaudio/best"
else:
# User specified explicit quality (1080p, 720p, etc.) for non-cam platforms
effective_quality = quality
cmd = ["yt-dlp", "--no-part"]
if platform not in _no_live_from_start:
cmd += ["--live-from-start", "--hls-use-mpegts"]
# Limit ffmpeg thread count — critical for Pi / low-power CPUs
ffmpeg_threads = get_ffmpeg_threads()
cmd += [
"--retries", "infinite", "--fragment-retries", "infinite",
"--retry-sleep", "5", "--socket-timeout", "30",
"--no-warnings", "--newline",
"--concurrent-fragments", "1",
"--fixup", "force",
"--downloader-args", f"ffmpeg:-threads {ffmpeg_threads} -fflags +genpts+discardcorrupt",
"-f", effective_quality,
"--merge-output-format", fmt,
"--progress", "--print", "after_move:filepath",
]
# On Pi / low-memory systems, cap the download buffer to reduce RAM usage
if _is_pi():
cmd += ["--buffer-size", "32K"]
# Chaturbate (and similar HLS cam sites) have audio segments that start
# exactly 1 second ahead of video — delay audio by 1s to compensate.
if platform in _cam_platforms:
cmd += ["--postprocessor-args", "ffmpeg:-c:v copy -c:a aac -af adelay=1000|1000"]
# Proxy (channel > global)
proxy = ch.get("proxy") or settings.get("proxy", "")
if proxy:
cmd += ["--proxy", proxy]
# Cookies file (channel > global)
cf_name = ch.get("cookies_file") or settings.get("cookies_file", "")
if cf_name:
cf = Path(cf_name) if Path(cf_name).is_absolute() else COOKIES_DIR / cf_name
if cf.exists():
cmd += ["--cookies", str(cf)]
# Username / password for age-restricted sites
ch_user = ch.get("ch_username", "")
ch_pass = ch.get("ch_password", "")
if ch_user:
cmd += ["--username", ch_user]
if ch_pass:
cmd += ["--password", ch_pass]
# Extra yt-dlp args (channel > global)
extra = ch.get("extra_args") or settings.get("extra_args", "")
if extra:
try:
# shlex.split is POSIX by default; on Windows use posix=False
cmd += shlex.split(extra, posix=not IS_WINDOWS)
except Exception:
pass
cmd += ["-o", str(output_path), url]
rec["status"] = "recording"
rec["started_at"] = time.time()
rec["log"] = []
size_task = None
proc = None
file_captured = False # pre-init so `finally` can read it even if we fail early
logger.info("Recording started: %s for %s (%s)", rec_id, username, url)
# If a stop/kill was requested before the task got scheduled, bail out now.
if rec.get("stopping"):
rec["status"] = "completed"
rec["ended_at"] = time.time()
if (ch_id := rec.get("channel_id")) and ch_id in channels:
channels[ch_id]["recording_id"] = None
_save_state()
return
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT,
**_subprocess_kwargs(),
)
rec["pid"] = proc.pid
# Race: stop was requested between starting and pid assignment — kill now.
if rec.get("stopping"):
_kill_proc(proc.pid, force=False)
async def _poll_size():
last_bytes = 0
last_time = time.time()
while True:
await asyncio.sleep(get_size_poll_interval())
for f in rec_dir.glob(f"{stem}.*"):
try:
sz = f.stat().st_size
if sz > 0:
now = time.time()
delta_bytes = sz - last_bytes
delta_time = now - last_time
if delta_time > 0 and last_bytes > 0 and delta_bytes >= 0:
bps = delta_bytes / delta_time
if bps >= 1024**2:
rec["speed"] = f"{bps/1024**2:.1f}MiB/s"
elif bps >= 1024:
rec["speed"] = f"{bps/1024:.1f}KiB/s"
else:
rec["speed"] = f"{bps:.0f}B/s"
last_bytes = sz
last_time = now
rec["bytes"] = sz
except Exception:
pass
break
size_task = asyncio.create_task(_poll_size())
rec_dir_str = str(RECORDINGS_DIR)
async for raw_line in proc.stdout:
# ffmpeg uses \r to overwrite progress; split on both \r and \n
for line in raw_line.decode("utf-8", errors="replace").replace("\r", "\n").split("\n"):
line = line.strip()
if not line:
continue
rec["log"].append(line)
log_max, log_trim = get_log_limits()
if len(rec["log"]) > log_max:
rec["log"] = rec["log"][-log_trim:]
# ffmpeg progress line (HLS via ffmpeg downloader):
# "frame= 49 fps=0.0 size= 256KiB time=00:00:01 bitrate=1279.8kbits/s speed= 3.2x"
if "frame=" in line and "bitrate=" in line:
m_size = re.search(r"size=\s*(\d+\.?\d*)\s*(GiB|MiB|KiB|B)\b", line)
if m_size:
v = float(m_size.group(1))
u = {"GiB": 1024**3, "MiB": 1024**2, "KiB": 1024, "B": 1}[m_size.group(2)]
rec["bytes"] = int(v * u)
m_br = re.search(r"bitrate=\s*(\d+\.?\d*\s*\w+bits/s)", line)
if m_br:
rec["speed"] = m_br.group(1)
# yt-dlp download progress line (HTTP downloads)
elif "[download]" in line or "[hlsnative]" in line:
m = re.search(r"(\d+\.?\d*)\s*(GiB|MiB|KiB|B)\b", line)
if m:
v = float(m.group(1))
u = {"GiB": 1024**3, "MiB": 1024**2, "KiB": 1024, "B": 1}[m.group(2)]
rec["bytes"] = int(v * u)
m2 = re.search(r"(\d+\.?\d*\s*(?:GiB|MiB|KiB|B)/s)", line)
if m2:
rec["speed"] = m2.group(1)
# Detect final filepath printed by --print after_move:filepath
if (not line.startswith("[") and not line.startswith("ERROR")
and len(line) > 4 and rec_dir_str in line):
p = Path(line)
if p.suffix:
rec["filepath"] = line
rec["filename"] = p.name
await proc.wait()
rc = proc.returncode
# Resolve filepath now (before status check) in case --print didn't fire
if not rec.get("filepath"):
for f in rec_dir.glob(f"{stem}.*"):
rec["filepath"] = str(f)
rec["filename"] = f.name
break
# Treat as completed if manually stopped OR if a file with real content was captured
# (yt-dlp exits non-zero when broadcaster goes offline, even after a full capture)
file_captured = bool(rec.get("filepath") and Path(rec["filepath"]).exists()
and Path(rec["filepath"]).stat().st_size > 0)
rec["status"] = "completed" if (rc == 0 or rec.get("stopping") or file_captured) else "error"
if rc != 0 and not rec.get("stopping") and not file_captured:
rec["error"] = f"Exit code {rc}"
logger.warning("Recording %s failed with exit code %d", rec_id, rc)
else:
logger.info("Recording %s completed", rec_id)
except asyncio.CancelledError:
rec["status"] = "completed" if rec.get("stopping") else "error"
if not rec.get("stopping"):
rec["error"] = "Cancelled"
raise
except Exception as e:
rec["status"] = "error"
rec["error"] = str(e)
logger.error("Recording %s exception: %s", rec_id, e)
finally:
if size_task:
size_task.cancel()
# Make sure we never leave an orphaned yt-dlp subprocess running
if proc is not None and proc.returncode is None:
try:
_kill_proc(proc.pid, force=False)
try:
await asyncio.wait_for(proc.wait(), timeout=5)
except asyncio.TimeoutError:
_kill_proc(proc.pid, force=True)
try:
await asyncio.wait_for(proc.wait(), timeout=2)
except asyncio.TimeoutError:
pass
except Exception:
pass
rec["ended_at"] = time.time()
rec.pop("pid", None)
# Fall back to file glob if yt-dlp didn't print the path
if not rec.get("filepath"):
for f in rec_dir.glob(f"{stem}.*"):
rec["filepath"] = str(f)
rec["filename"] = f.name
break
if fp := rec.get("filepath"):
try:
rec["bytes"] = Path(fp).stat().st_size
except Exception:
pass
# Remux to fix containers and move moov atom to file start for
# smooth playback (faststart). Run on ALL completed recordings —
# not just manual stops — so files play without lag on any device.
fp = rec.get("filepath", "")
if fp and Path(fp).exists():
suffix = Path(fp).suffix
fixed_path = str(Path(fp).with_name(Path(fp).stem + "_fixed" + suffix))
try:
fix_proc = await asyncio.create_subprocess_exec(
"ffmpeg", "-i", fp, "-c", "copy", "-movflags", "+faststart",
"-threads", ffmpeg_threads, fixed_path, "-y",
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
await asyncio.wait_for(fix_proc.wait(), timeout=REMUX_TIMEOUT)
if fix_proc.returncode == 0 and Path(fixed_path).exists():
Path(fp).unlink(missing_ok=True)
Path(fixed_path).rename(fp)
try:
rec["bytes"] = Path(fp).stat().st_size
except Exception:
pass
else:
Path(fixed_path).unlink(missing_ok=True)
except Exception:
try:
Path(fixed_path).unlink(missing_ok=True)
except Exception:
pass
# Optional MP4 conversion
auto_convert = ch.get("auto_convert_mp4", settings["auto_convert_mp4"])
delete_orig = ch.get("delete_original", settings["delete_original"])
fp = rec.get("filepath", "")
if auto_convert and fp and not fp.endswith(".mp4") and Path(fp).exists():
mp4_path = str(Path(fp).with_suffix(".mp4"))
try:
conv = await asyncio.create_subprocess_exec(
"ffmpeg", "-i", fp, "-c", "copy",
"-movflags", "+faststart",
"-threads", ffmpeg_threads,
mp4_path, "-y",
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL,
)
await conv.wait()
if conv.returncode == 0:
if delete_orig:
Path(fp).unlink(missing_ok=True)
rec["filepath"] = mp4_path
rec["filename"] = Path(mp4_path).name
try:
rec["bytes"] = Path(mp4_path).stat().st_size
except Exception:
pass
except Exception:
pass
# Only clear the channel's recording pointer if it still points at US —
# a subsequent Record click could have already started a new rec_id.
if ch_id := rec.get("channel_id"):
ch_entry = channels.get(ch_id)
if ch_entry and ch_entry.get("recording_id") == rec_id:
ch_entry["recording_id"] = None
ch_entry["is_live"] = False
_save_state()
# Auto-retry on unexpected disconnect
retry_ch_id = rec.get("channel_id")
# Don't retry if stream ran for more than 30s — that's a natural end, not a crash
run_duration = (rec.get("ended_at") or time.time()) - (rec.get("started_at") or time.time())
natural_end = run_duration > 30 and file_captured
should_retry = (
not rec.get("stopping")
and not natural_end
and rec.get("status") == "error"
and settings.get("auto_retry", True)
and retry_ch_id
and retry_ch_id in channels
and channels[retry_ch_id].get("monitoring", True)
)
if should_retry:
attempt = rec.get("_retry_attempt", 0) + 1
max_retries = settings.get("max_retries", 5)
delay = settings.get("retry_delay", 15)
if attempt <= max_retries:
rec["log"].append(
f"[StreamRec] Stream disconnected. Retrying in {delay}s "
f"(attempt {attempt}/{max_retries})…"
)
await asyncio.sleep(delay)
if retry_ch_id in channels and not channels[retry_ch_id].get("recording_id"):
new_id = await _start_recording_for_channel(retry_ch_id)
if new_id:
recordings[new_id]["_retry_attempt"] = attempt
recordings[new_id]["auto"] = True
# ── Monitor loop ──────────────────────────────────────────────────────────────
async def _check_one_channel(ch_id: str) -> None:
"""Check a single channel's live state and auto-record if needed.
Runs per-channel error handling so one bad URL can't take down the tick.
"""
ch = channels.get(ch_id)
if not ch or not ch.get("monitoring", True):
return
existing = ch.get("recording_id")
if existing and existing in recordings:
r = recordings[existing]
if r.get("status") in ("recording", "starting"):
# Still recording — no need to re-check, just mark live
if ch_id in channels:
channels[ch_id]["is_live"] = True
channels[ch_id]["last_checked"] = time.time()
return
proxy = ch.get("proxy") or settings.get("proxy", "")
try:
is_live = await check_is_live(ch["url"], proxy=proxy)
except Exception as e:
logger.warning("Live check failed for %s (%s): %s", ch_id, ch.get("url"), e)
return
# Channel could have been deleted while we were awaiting
if ch_id not in channels:
return
channels[ch_id]["is_live"] = is_live
channels[ch_id]["last_checked"] = time.time()
if is_live and not channels[ch_id].get("recording_id"):
logger.info("Channel %s is live — starting auto-record", ch_id)
try:
rec_id = await _start_recording_for_channel(ch_id)
except Exception as e:
logger.exception("Failed to start auto-record for %s: %s", ch_id, e)
return
if rec_id and rec_id in recordings:
recordings[rec_id]["auto"] = True
async def monitor_loop():
while True:
interval = max(5, int(settings.get("monitor_interval", 60)))
await asyncio.sleep(interval)
ids = [cid for cid, c in channels.items() if c.get("monitoring", True)]
if not ids:
continue
logger.debug("Monitor tick — checking %d channels", len(ids))
# Run per-channel checks concurrently; gather never raises because
# each coroutine traps its own exceptions.
await asyncio.gather(
*(_check_one_channel(cid) for cid in ids),
return_exceptions=True,
)
# ── Request models ────────────────────────────────────────────────────────────
class AddChannelRequest(BaseModel):
url: str
quality: str = ""
format: str = ""
monitoring: bool = True
auto_convert_mp4: bool = False
delete_original: bool = False
record_now: bool = False
proxy: str = ""
cookies_file: str = ""
username: str = ""
password: str = ""
extra_args: str = ""
class UpdateChannelRequest(BaseModel):
monitoring: Optional[bool] = None
quality: Optional[str] = None
format: Optional[str] = None
auto_convert_mp4: Optional[bool] = None
delete_original: Optional[bool] = None
proxy: Optional[str] = None
cookies_file: Optional[str] = None
username: Optional[str] = None
password: Optional[str] = None
extra_args: Optional[str] = None
class UpdateSettingsRequest(BaseModel):
pi_mode: Optional[bool] = None
monitor_interval: Optional[int] = None
default_quality: Optional[str] = None
default_format: Optional[str] = None
auto_convert_mp4: Optional[bool] = None
delete_original: Optional[bool] = None
record_on_add: Optional[bool] = None
auto_retry: Optional[bool] = None
max_retries: Optional[int] = None
retry_delay: Optional[int] = None
proxy: Optional[str] = None
cookies_file: Optional[str] = None
extra_args: Optional[str] = None
class ReorderRequest(BaseModel):
order: list[str]
class BulkActionRequest(BaseModel):
ids: list[str]
action: str # "record" | "stop" | "delete"