|
import os |
|
import time |
|
import subprocess |
|
from multiprocessing import Process |
|
import uvicorn |
|
from fastapi import FastAPI, Response |
|
|
|
app = FastAPI() |
|
|
|
|
|
video_file = "iarec.mp4" |
|
hls_output = "stream.m3u8" |
|
hls_segment_prefix = "stream" |
|
|
|
|
|
ffmpeg_command = [ |
|
'./ffmpeg', |
|
'-re', |
|
'-stream_loop', '-1', |
|
'-i', video_file, |
|
'-vf', 'fps=24', |
|
'-c:v', 'libx264', |
|
'-c:a', 'copy', |
|
'-crf', '32', |
|
'-preset', 'fast', |
|
'-bsf:a', 'aac_adtstoasc', |
|
'-f', 'hls', |
|
'-hls_time', '15', |
|
'-hls_list_size', '15', |
|
'-hls_flags', 'append_list+omit_endlist', |
|
'-hls_segment_filename', f'{hls_segment_prefix}%03d.ts', |
|
hls_output |
|
] |
|
|
|
def make_ffmpeg_executable(): |
|
try: |
|
subprocess.run(["chmod", "+x", "./ffmpeg"], check=True) |
|
except subprocess.CalledProcessError as e: |
|
print(f"Error al cambiar permisos de FFmpeg: {e}") |
|
|
|
def stream_video(): |
|
try: |
|
process = subprocess.Popen(ffmpeg_command) |
|
process.wait() |
|
except Exception as e: |
|
print(f"Error al ejecutar FFmpeg: {e}") |
|
|
|
@app.on_event("startup") |
|
async def startup_event(): |
|
make_ffmpeg_executable() |
|
|
|
while not os.path.exists(hls_output): |
|
print("Esperando a que se genere el archivo M3U8...") |
|
time.sleep(1) |
|
print("Archivo M3U8 generado. Servidor listo para recibir solicitudes.") |
|
|
|
@app.get("/") |
|
async def read_root(): |
|
return {"message": "Training IA"} |
|
|
|
@app.get("/stream.m3u8") |
|
def get_m3u8(): |
|
with open(hls_output, "rb") as f: |
|
m3u8_content = f.read() |
|
return Response(content=m3u8_content, media_type="application/vnd.apple.mpegurl") |
|
|
|
@app.get("/stream{segment}.ts") |
|
def get_segment(segment: int): |
|
segment_file = f"{hls_segment_prefix}{segment:03d}.ts" |
|
if os.path.exists(segment_file): |
|
with open(segment_file, "rb") as f: |
|
segment_content = f.read() |
|
return Response(content=segment_content, media_type="video/mp2t") |
|
else: |
|
return Response(status_code=404, content="Segment not found") |
|
|
|
if __name__ == "__main__": |
|
|
|
make_ffmpeg_executable() |
|
video_process = Process(target=stream_video) |
|
video_process.start() |
|
uvicorn.run(app, host="0.0.0.0", port=7860) |