CineMax commited on
Commit
9ceb596
·
verified ·
1 Parent(s): 8344315

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -47
app.py CHANGED
@@ -14,13 +14,14 @@ app.add_middleware(
14
  allow_headers=["*"],
15
  )
16
 
17
- DIRECTORIO_HLS = "/tmp/hls_en_vivo"
18
  os.makedirs(DIRECTORIO_HLS, exist_ok=True)
19
 
20
  app.mount("/hls", StaticFiles(directory=DIRECTORIO_HLS), name="hls")
21
 
22
  proceso_ffmpeg = None
23
 
 
24
  @app.get("/iniciar-transmision")
25
  def iniciar_transmision(url: str):
26
  global proceso_ffmpeg
@@ -31,53 +32,49 @@ def iniciar_transmision(url: str):
31
 
32
  os.system(f"rm -rf {DIRECTORIO_HLS}/*")
33
 
 
34
  probe = subprocess.run(
35
  ["ffprobe", "-v", "error", "-select_streams", "a",
36
  "-show_entries", "stream=index", "-of", "csv=p=0", url],
37
  capture_output=True, text=True, timeout=15
38
  )
39
  pistas_audio = [l for l in probe.stdout.strip().splitlines() if l.strip()]
40
- tiene_dos_audios = len(pistas_audio) >= 2
41
-
42
- if tiene_dos_audios:
43
- comando = [
44
- "ffmpeg", "-y",
45
- "-i", url, # Sin -re → convierte tan rápido como puede
46
- "-map", "0:v:0", "-map", "0:a:0",
47
- "-map", "0:a:1",
48
- "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
49
- "-profile:v", "baseline", "-level", "3.0",
50
- "-g", "48", "-keyint_min", "48", "-sc_threshold", "0",
51
- "-c:a", "aac", "-b:a", "128k", "-ac", "2",
52
- "-f", "hls",
53
- "-hls_time", "6",
54
- "-hls_list_size", "0",
55
- "-hls_playlist_type", "event", # EVENT: agrega segmentos en tiempo real + seek completo al terminar
56
- "-hls_flags", "independent_segments",
57
- "-hls_segment_type", "mpegts",
58
- "-hls_segment_filename", f"{DIRECTORIO_HLS}/seg_%v_%03d.ts",
59
- "-master_pl_name", "master.m3u8",
60
- "-var_stream_map", "v:0,a:0,name:esp a:1,name:eng",
61
- f"{DIRECTORIO_HLS}/playlist_%v.m3u8"
62
- ]
63
- else:
64
- comando = [
65
- "ffmpeg", "-y",
66
- "-i", url, # Sin -re
67
- "-map", "0:v:0", "-map", "0:a:0",
68
- "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
69
- "-profile:v", "baseline", "-level", "3.0",
70
- "-g", "48", "-keyint_min", "48", "-sc_threshold", "0",
71
- "-c:a", "aac", "-b:a", "128k", "-ac", "2",
72
- "-f", "hls",
73
- "-hls_time", "6",
74
- "-hls_list_size", "0",
75
- "-hls_playlist_type", "event", # EVENT: carga sin esperar, seek total al terminar
76
- "-hls_flags", "independent_segments",
77
- "-hls_segment_type", "mpegts",
78
- "-hls_segment_filename", f"{DIRECTORIO_HLS}/seg_%03d.ts",
79
- f"{DIRECTORIO_HLS}/playlist_0.m3u8"
80
- ]
81
 
82
  proceso_ffmpeg = subprocess.Popen(
83
  comando,
@@ -87,18 +84,34 @@ def iniciar_transmision(url: str):
87
 
88
  return {
89
  "estado": "Procesando",
90
- "audios_detectados": len(pistas_audio),
91
  "url_master": "https://cinemax-mp4.hf.space/hls/master.m3u8",
92
  "url_directa": "https://cinemax-mp4.hf.space/hls/playlist_0.m3u8",
93
  }
94
 
95
 
96
- @app.get("/estado")
97
- def estado():
 
98
  global proceso_ffmpeg
99
- vivo = proceso_ffmpeg is not None and proceso_ffmpeg.poll() is None
 
 
 
100
  segmentos = len([f for f in os.listdir(DIRECTORIO_HLS) if f.endswith(".ts")])
101
- return {"ffmpeg_activo": vivo, "segmentos_generados": segmentos}
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
 
104
  @app.get("/detener")
 
14
  allow_headers=["*"],
15
  )
16
 
17
+ DIRECTORIO_HLS = "/tmp/hls_vod"
18
  os.makedirs(DIRECTORIO_HLS, exist_ok=True)
19
 
20
  app.mount("/hls", StaticFiles(directory=DIRECTORIO_HLS), name="hls")
21
 
22
  proceso_ffmpeg = None
23
 
24
+
25
  @app.get("/iniciar-transmision")
26
  def iniciar_transmision(url: str):
27
  global proceso_ffmpeg
 
32
 
33
  os.system(f"rm -rf {DIRECTORIO_HLS}/*")
34
 
35
+ # Detectar TODAS las pistas de audio
36
  probe = subprocess.run(
37
  ["ffprobe", "-v", "error", "-select_streams", "a",
38
  "-show_entries", "stream=index", "-of", "csv=p=0", url],
39
  capture_output=True, text=True, timeout=15
40
  )
41
  pistas_audio = [l for l in probe.stdout.strip().splitlines() if l.strip()]
42
+ num_audios = len(pistas_audio)
43
+ if num_audios == 0:
44
+ num_audios = 1 # fallback
45
+
46
+ # Construir -map dinámicamente para todas las pistas
47
+ mapeos = ["-map", "0:v:0"]
48
+ for i in range(num_audios):
49
+ mapeos += ["-map", f"0:a:{i}"]
50
+
51
+ # var_stream_map: video va con audio 0, resto son pistas independientes
52
+ # Nombres de idioma genéricos si no sabemos cuáles son
53
+ nombres = ["audio1", "audio2", "audio3", "audio4"]
54
+ stream_map_parts = ["v:0,a:0,name:" + nombres[0]]
55
+ for i in range(1, num_audios):
56
+ stream_map_parts.append(f"a:{i},name:{nombres[i]}")
57
+ var_stream_map = " ".join(stream_map_parts)
58
+
59
+ comando = [
60
+ "ffmpeg", "-y",
61
+ "-i", url,
62
+ *mapeos,
63
+ "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
64
+ "-profile:v", "baseline", "-level", "3.0",
65
+ "-g", "48", "-keyint_min", "48", "-sc_threshold", "0",
66
+ "-c:a", "aac", "-b:a", "128k", "-ac", "2",
67
+ "-f", "hls",
68
+ "-hls_time", "6",
69
+ "-hls_list_size", "0",
70
+ "-hls_playlist_type", "vod", # VOD real: escribe #EXT-X-ENDLIST al terminar
71
+ "-hls_flags", "independent_segments",
72
+ "-hls_segment_type", "mpegts",
73
+ "-hls_segment_filename", f"{DIRECTORIO_HLS}/seg_%v_%03d.ts",
74
+ "-master_pl_name", "master.m3u8",
75
+ "-var_stream_map", var_stream_map,
76
+ f"{DIRECTORIO_HLS}/playlist_%v.m3u8"
77
+ ]
 
 
 
 
 
78
 
79
  proceso_ffmpeg = subprocess.Popen(
80
  comando,
 
84
 
85
  return {
86
  "estado": "Procesando",
87
+ "audios_detectados": num_audios,
88
  "url_master": "https://cinemax-mp4.hf.space/hls/master.m3u8",
89
  "url_directa": "https://cinemax-mp4.hf.space/hls/playlist_0.m3u8",
90
  }
91
 
92
 
93
+ @app.get("/listo")
94
+ def listo():
95
+ """El PHP hace polling aquí hasta que FFmpeg termina."""
96
  global proceso_ffmpeg
97
+ if proceso_ffmpeg is None:
98
+ return {"listo": False, "razon": "Sin proceso"}
99
+
100
+ activo = proceso_ffmpeg.poll() is None
101
  segmentos = len([f for f in os.listdir(DIRECTORIO_HLS) if f.endswith(".ts")])
102
+
103
+ # VOD está listo cuando FFmpeg terminó Y el m3u8 tiene #EXT-X-ENDLIST
104
+ vod_listo = False
105
+ playlist = f"{DIRECTORIO_HLS}/playlist_0.m3u8"
106
+ if not activo and os.path.exists(playlist):
107
+ with open(playlist) as f:
108
+ vod_listo = "#EXT-X-ENDLIST" in f.read()
109
+
110
+ return {
111
+ "listo": vod_listo,
112
+ "ffmpeg_activo": activo,
113
+ "segmentos": segmentos
114
+ }
115
 
116
 
117
  @app.get("/detener")