54 lines
1.4 KiB
Python
54 lines
1.4 KiB
Python
import subprocess
|
|
import time
|
|
from pathlib import Path
|
|
|
|
VIDEOS_DIR = "/videos"
|
|
|
|
|
|
def stream_video_live(video_id: int, youtube_url: str):
|
|
output_path = f"{VIDEOS_DIR}/{video_id}.mp4"
|
|
path = Path(output_path)
|
|
|
|
process = subprocess.Popen(
|
|
[
|
|
"yt-dlp",
|
|
"-f", "best[ext=mp4][vcodec^=avc]/best[ext=mp4]",
|
|
"-o", output_path,
|
|
youtube_url,
|
|
],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
|
|
# Warte bis Datei existiert und mindestens 1MB hat
|
|
while process.poll() is None:
|
|
if path.exists() and path.stat().st_size >= 1024 * 1024:
|
|
break
|
|
time.sleep(0.5)
|
|
|
|
if not path.exists():
|
|
process.wait()
|
|
return
|
|
|
|
# Streame aus der wachsenden Datei
|
|
pos = 0
|
|
stall_count = 0
|
|
with open(output_path, "rb") as f:
|
|
while True:
|
|
chunk = f.read(1024 * 1024)
|
|
if chunk:
|
|
pos += len(chunk)
|
|
stall_count = 0
|
|
yield chunk
|
|
else:
|
|
if process.poll() is not None:
|
|
# Download fertig — restliche Bytes lesen
|
|
remaining = f.read()
|
|
if remaining:
|
|
yield remaining
|
|
break
|
|
stall_count += 1
|
|
if stall_count > 60: # 30 Sekunden ohne neue Daten
|
|
break
|
|
time.sleep(0.5)
|