restest / app.py
haxwitcher's picture
Update app.py
c9551f0 verified
Raw History Blame Contribute Delete
2.13 kB
# app.py
import os
import subprocess
import pathlib
from typing import Dict
from fastapi import FastAPI
from fastapi.responses import FileResponse, JSONResponse
app = FastAPI()
ffmpeg_processes: Dict[str, subprocess.Popen] = {}
HLS_ROOT = pathlib.Path("hls")
HLS_ROOT.mkdir(exist_ok=True)
def stop_stream(stream_id: str):
process = ffmpeg_processes.get(stream_id)
if process and process.poll() is None:
print(f"[INFO] Zaustavljam prethodni stream: {stream_id}")
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
def start_stream(stream_id: str, source_url: str):
stop_stream(stream_id) # zaustavi prethodni ako postoji
stream_dir = HLS_ROOT / stream_id
if stream_dir.exists():
for f in stream_dir.glob("*"):
f.unlink()
stream_dir.mkdir(parents=True, exist_ok=True)
ffmpeg_cmd = [
"ffmpeg",
"-fflags", "+genpts",
"-i", source_url,
"-c:v", "copy",
"-c:a", "copy",
"-f", "hls",
"-hls_time", "4",
"-hls_list_size", "5",
"-hls_flags", "delete_segments+program_date_time",
str(stream_dir / "stream.m3u8")
]
print(f"[INFO] Pokrećem stream: {stream_id}")
process = subprocess.Popen(
ffmpeg_cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT
)
ffmpeg_processes[stream_id] = process
# Učitaj sve STREAM_* varijable i pokreni
for key, value in os.environ.items():
if key.startswith("STREAM_"):
stream_id = key[len("STREAM_"):].lower()
start_stream(stream_id, value)
@app.get("/hls/{stream_id}/{path:path}")
def serve_hls(stream_id: str, path: str):
file_path = HLS_ROOT / stream_id / path
if file_path.exists():
return FileResponse(file_path)
return JSONResponse({"error": "ne postoji"}, status_code=404)
@app.get("/")
def index():
links = {
stream_id: f"/hls/{stream_id}/stream.m3u8"
for stream_id in ffmpeg_processes
}
return {"status": "aktivni streamovi", "streams": links}