CineMax commited on
Commit
d94f6d6
·
verified ·
1 Parent(s): a5e6513

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -18
app.py CHANGED
@@ -2,6 +2,8 @@ import subprocess
2
  import os
3
  import json
4
  import uvicorn
 
 
5
  from fastapi import FastAPI
6
  from fastapi.staticfiles import StaticFiles
7
  from fastapi.middleware.cors import CORSMiddleware
@@ -14,16 +16,25 @@ app.add_middleware(
14
  allow_methods=["*"],
15
  )
16
 
17
- DIRECTORIO_HLS = "/tmp/hls_en_vivo"
18
- os.makedirs(DIRECTORIO_HLS, exist_ok=True)
19
- app.mount("/hls", StaticFiles(directory=DIRECTORIO_HLS), name="hls")
 
20
 
21
  @app.get("/iniciar-transmision")
22
  def iniciar_transmision(url: str):
23
- # 1. Limpiar el proceso anterior
24
- os.system(f"rm -rf {DIRECTORIO_HLS}/*")
 
25
 
26
- # 2. Analizar el MP4 para saber exactamente cuántos audios tiene
 
 
 
 
 
 
 
27
  probe_cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", url]
28
  probe_res = subprocess.run(probe_cmd, capture_output=True, text=True)
29
 
@@ -40,37 +51,44 @@ def iniciar_transmision(url: str):
40
  "lang": stream.get("tags", {}).get("language", "und")
41
  })
42
 
43
- # 3. Construir el comando FFmpeg para separar pistas dinámicamente
44
  cmd = ["ffmpeg", "-y", "-i", url, "-map", "0:v:0"]
45
-
46
- # Aquí creamos el "Audio Group" que JW Player necesita para mostrar el menú
47
  var_stream_map = "v:0,agroup:audios"
48
 
49
  for i, a in enumerate(audios):
50
  cmd.extend(["-map", f"0:{a['index']}"])
51
  lang = a['lang']
52
- # Separamos cada pista y le asignamos su idioma
53
  var_stream_map += f" a:{i},agroup:audios,language:{lang},name:Audio_{i+1}_{lang.upper()}"
54
 
55
- # 4. Configurar la salida HLS para que empiece desde cero (EVENT)
56
  cmd.extend([
57
  "-c", "copy",
58
  "-f", "hls",
59
- "-hls_time", "6", # Fragmentos más cortos para que cargue más rápido
60
  "-hls_list_size", "0",
61
- "-hls_playlist_type", "event", # ESTO OBLIGA A EMPEZAR DESDE EL SEGUNDO 0
62
- "-hls_segment_filename", f"{DIRECTORIO_HLS}/pedazo_%v_%03d.ts",
63
  "-master_pl_name", "master.m3u8",
64
  "-var_stream_map", var_stream_map,
65
- f"{DIRECTORIO_HLS}/playlist_%v.m3u8"
66
  ])
67
 
68
- # 5. Lanzar el proceso en segundo plano (Empaquetado dinámico)
69
  subprocess.Popen(cmd)
70
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  return {
72
- "estado": "Procesando correctamente",
73
- "url_reproductor": "https://cinemax-mp4.hf.space/hls/master.m3u8"
74
  }
75
 
76
  if __name__ == "__main__":
 
2
  import os
3
  import json
4
  import uvicorn
5
+ import hashlib
6
+ import time
7
  from fastapi import FastAPI
8
  from fastapi.staticfiles import StaticFiles
9
  from fastapi.middleware.cors import CORSMiddleware
 
16
  allow_methods=["*"],
17
  )
18
 
19
+ # Carpeta base para todos los streams
20
+ BASE_HLS = "/tmp/streams"
21
+ os.makedirs(BASE_HLS, exist_ok=True)
22
+ app.mount("/hls", StaticFiles(directory=BASE_HLS), name="hls")
23
 
24
  @app.get("/iniciar-transmision")
25
  def iniciar_transmision(url: str):
26
+ # Crear un identificador único para este video (así no chocan si hay varios usuarios)
27
+ hash_video = hashlib.md5(url.encode()).hexdigest()
28
+ dir_video = f"{BASE_HLS}/{hash_video}"
29
 
30
+ # Si el archivo maestro ya existe, no volvemos a procesar, servimos directo al instante
31
+ master_file = f"{dir_video}/master.m3u8"
32
+ if os.path.exists(master_file):
33
+ return {"url_reproductor": f"https://cinemax-mp4.hf.space/hls/{hash_video}/master.m3u8"}
34
+
35
+ os.makedirs(dir_video, exist_ok=True)
36
+
37
+ # Analizar el MP4
38
  probe_cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", url]
39
  probe_res = subprocess.run(probe_cmd, capture_output=True, text=True)
40
 
 
51
  "lang": stream.get("tags", {}).get("language", "und")
52
  })
53
 
54
+ # Construir FFmpeg
55
  cmd = ["ffmpeg", "-y", "-i", url, "-map", "0:v:0"]
 
 
56
  var_stream_map = "v:0,agroup:audios"
57
 
58
  for i, a in enumerate(audios):
59
  cmd.extend(["-map", f"0:{a['index']}"])
60
  lang = a['lang']
 
61
  var_stream_map += f" a:{i},agroup:audios,language:{lang},name:Audio_{i+1}_{lang.upper()}"
62
 
 
63
  cmd.extend([
64
  "-c", "copy",
65
  "-f", "hls",
66
+ "-hls_time", "2", # ¡CLAVE! Fragmentos de 2 segundos para que arranque instantáneo
67
  "-hls_list_size", "0",
68
+ "-hls_playlist_type", "event",
69
+ "-hls_segment_filename", f"{dir_video}/pedazo_%v_%03d.ts",
70
  "-master_pl_name", "master.m3u8",
71
  "-var_stream_map", var_stream_map,
72
+ f"{dir_video}/playlist_%v.m3u8"
73
  ])
74
 
75
+ # Lanzar FFmpeg
76
  subprocess.Popen(cmd)
77
 
78
+ # ¡LA MAGIA AQUÍ! El script espera hasta que el archivo m3u8 realmente exista (máximo 10 segundos)
79
+ tiempo_espera = 0
80
+ while not os.path.exists(master_file) and tiempo_espera < 10:
81
+ time.sleep(0.5)
82
+ tiempo_espera += 0.5
83
+
84
+ if not os.path.exists(master_file):
85
+ return {"error": "FFmpeg tardó demasiado en iniciar. Revisa el peso del MP4."}
86
+
87
+ # Le damos 1 segundito extra para que escupa el primer pedazo de video .ts
88
+ time.sleep(1)
89
+
90
  return {
91
+ "url_reproductor": f"https://cinemax-mp4.hf.space/hls/{hash_video}/master.m3u8"
 
92
  }
93
 
94
  if __name__ == "__main__":