File size: 3,431 Bytes
ffd22a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import time
import subprocess
import random
from multiprocessing import Process
import uvicorn
from fastapi import FastAPI, Response
import py7zr

app = FastAPI()

# Carpeta de videos y rutas de salida
video_folder = "Los Simpsons"
hls_output = "stream.m3u8"
hls_segment_prefix = "stream"
concat_file = "concat.txt"

# Funci贸n para descargar y descomprimir el archivo 7z
def download_and_extract_videos():
    video_file = "Los Simpsons.7z"
    download_path = os.path.join(video_folder, video_file)
    extract_path = os.path.join(video_folder)
    subprocess.run(["wget", "https://huggingface.co/spaces/lozanogamer/lozanogamers/resolve/main/Los%20Simpsons.7z?download=true", "-P", video_folder])
    with py7zr.SevenZipFile(download_path, 'r') as archive:
        archive.extractall(path=extract_path)
    os.remove(download_path)

# Funci贸n para generar un archivo de concatenaci贸n de videos
def generate_concat_file():
    video_files = os.listdir(video_folder)
    with open(concat_file, "w") as f:
        for video_file in video_files:
            if video_file.endswith(".mp4"):
                f.write(f"file '{os.path.join(video_folder, video_file)}'\n")

# Comando FFmpeg para transmitir video en HLS
def build_ffmpeg_command():
    return [
        'ffmpeg',
        '-re',
        '-f', 'concat',
        '-safe', '0',
        '-i', concat_file,
        '-c:v', 'libx264',
        '-c:a', 'aac',
        '-b:v', '2000k',
        '-b:a', '128k',
        '-f', 'hls',
        '-hls_time', '10',
        '-hls_list_size', '0',
        '-hls_flags', 'delete_segments',
        '-hls_segment_filename', f'{hls_segment_prefix}%d.ts',
        hls_output
    ]

def stream_video():
    # Descarga y descomprime el archivo de video
    download_and_extract_videos()

    # Ejecuta el comando FFmpeg para iniciar la transmisi贸n
    while True:
        generate_concat_file()
        ffmpeg_command = build_ffmpeg_command()
        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": "Servidor de Streaming de Videos M3U8 Activo"}

@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}.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)