File size: 2,338 Bytes
4245151
 
 
 
 
 
 
 
 
 
 
 
 
 
170b099
4245151
 
 
170b099
4245151
6e156d8
 
4245151
 
3d1e812
 
170b099
3d1e812
4245151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42ef622
4245151
 
 
 
 
 
 
 
6095d64
4245151
 
3d1e812
4245151
 
 
 
 
 
 
 
 
e686c81
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
import os
import time
import subprocess
from multiprocessing import Process
import uvicorn
from fastapi import FastAPI, Response

app = FastAPI()

# Archivo de video y rutas de salida
video_file = "iarec.mp4"
hls_output = "stream.m3u8"
hls_segment_prefix = "stream"

# Comando FFmpeg para transmitir video en HLS (en loop continuo)
ffmpeg_command = [
    'ffmpeg',
    '-re',
    '-stream_loop', '-1',  # Repetir el video en loop
    '-i', video_file,
    '-c:v', 'copy',
    '-c:a', 'aac',
    '-preset', 'ultrafast',
    '-f', 'hls',
    '-hls_time', '10',  # Duraci贸n de cada segmento en segundos
    '-hls_list_size', '10',  # N煤mero de segmentos en la lista de reproducci贸n
    '-hls_flags', 'append_list+omit_endlist',  # A帽adir a la lista sin eliminar los antiguos
    '-hls_segment_filename', f'{hls_segment_prefix}%03d.ts',  # Nombre de archivo de los segmentos
    hls_output
]

def stream_video():
    # Ejecuta el comando FFmpeg para iniciar la transmisi贸n
    process = subprocess.Popen(ffmpeg_command)
    process.wait()

def start_video_streaming():
    video_process = Process(target=stream_video)
    video_process.start()

@app.on_event("startup")
async def startup_event():
    # Espera activa para verificar que el archivo M3U8 est茅 generado
    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": "Streaming 24/7 in loop"}

@app.get("/stream.m3u8")
def get_m3u8():
    # Devuelve el archivo M3U8 generado
    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):
    # Devuelve los segmentos TS generados
    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__":
    start_video_streaming()
    uvicorn.run(app, host="0.0.0.0", port=7860)