OrbiSubs: master advertises the real resolution and bitrate; players jump to live by hand

The master playlist had BANDWIDTH and RESOLUTION hard-coded to T13's values
(2.6 Mb/s, 1280x720), so ecuadortv (1080p60, ~8 Mb/s) was announced as 720p.
They are now measured from the ingest's own segments in a side thread and the
master is rewritten when they change; --bandwidth/--resolution still pin them.

4f7a685 passed liveMaxLatencyDurationCount alone, which hls.js rejects
("Illegal hls.js config"), so no channel played in player.html or in the
panel's preview. The jump back to live is now done on LEVEL_UPDATED, which
keeps the HOLD-BACK published by the channel as the target.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
guy
2026-11-18 22:28:08 -05:00
parent 4f7a685571
commit a6668f1601
3 changed files with 111 additions and 13 deletions
+92 -11
View File
@@ -345,6 +345,92 @@ def escribir_vtt(path, cues, s0, s1, ajustes="", ya=None):
escribir_atomico(path, "\n".join(cuerpo) + "\n") escribir_atomico(path, "\n".join(cuerpo) + "\n")
class Master:
"""master.m3u8 con la resolución y el bitrate que de verdad trae la señal.
Antes iban fijos (1280x720 y 2,6 Mb/s, los de T13 en la 076) y cualquier otro canal
anunciaba eso: ecuadortv, que es 1080p60 a ~8 Mb/s, salía como 720p (2026-11-19).
Con una sola calidad hls.js no lo usa, pero un player de TV o un packager que elige
por BANDWIDTH sí. Se mide en un hilo aparte, sobre los .ts que ya escribió la
ingesta, para no sumarle nada al camino del subtítulo.
"""
CADA = 60.0 # cada cuánto se vuelve a medir (la señal puede cambiar)
def __init__(self, a):
self.a = a
self.res = a.resolution
self.bw = a.bandwidth
self.picos = deque(maxlen=20) # bitrate de los últimos segmentos medidos
def escribir(self):
a = self.a
attrs = f"BANDWIDTH={self.bw or 2600000}"
if self.res:
attrs += f",RESOLUTION={self.res}"
escribir_atomico(os.path.join(a.dir, "master.m3u8"),
"#EXTM3U\n#EXT-X-VERSION:3\n"
f'#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="{LANG_NAMES[LANG]}",LANGUAGE="{LANG}",'
'DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,URI="subs.m3u8"\n'
+ ('#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="English (automatic)",LANGUAGE="en",'
'DEFAULT=NO,AUTOSELECT=NO,FORCED=NO,URI="en.m3u8"\n' if a.en else "")
+ f'#EXT-X-STREAM-INF:{attrs},SUBTITLES="subs"\n'
"video.m3u8\n")
def medir(self, src):
"""Resolución del último .ts completo y bitrate de cada segmento nuevo."""
segs, _ = leer_lista(src)
if len(segs) < 2:
return False
nuevo = False
for seq, uri, dur, _ in segs[:-1]: # el último puede estar escribiéndose
if seq in self.vistos or not dur:
continue
self.vistos.add(seq)
try:
self.picos.append(os.path.getsize(os.path.join(os.path.dirname(src), uri)) * 8 / dur)
nuevo = True
except OSError:
pass
if not nuevo:
return False
cambio = False
if self.a.resolution is None:
path = os.path.join(os.path.dirname(src), segs[-2][1])
pr = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
"stream=width,height", "-of", "csv=p=0:s=x", path],
capture_output=True, text=True)
res = pr.stdout.strip().splitlines()[0] if pr.returncode == 0 and pr.stdout.strip() else None
if res and res != self.res:
self.res, cambio = res, True
if self.a.bandwidth is None and self.picos:
# HLS pide el pico: el máximo de los últimos segmentos, redondeado a 100 kb/s.
# Solo se reescribe si cambió más de un 20 %, para no tocar el master a cada rato.
bw = int(max(self.picos) / 100000 + 1) * 100000
if not self.bw or abs(bw - self.bw) > 0.2 * self.bw:
self.bw, cambio = bw, True
if cambio:
self.escribir()
log("master", resolution=self.res, bandwidth=self.bw)
return True
def arrancar(self, src):
if self.a.resolution and self.a.bandwidth:
return
import threading
self.vistos = set()
def bucle():
prox = 0
while True:
try:
if time.time() >= prox and self.medir(src):
prox = time.time() + self.CADA
except Exception as e: # nunca tirar abajo el ASR por esto
log("master_error", err=str(e)[:200])
time.sleep(2)
threading.Thread(target=bucle, daemon=True, name="master").start()
def publicar_listas(a, segs, tgt, publicado, subs_dir): def publicar_listas(a, segs, tgt, publicado, subs_dir):
"""video.m3u8 y subs.m3u8 hasta el último segmento con subtítulo. Devuelve el """video.m3u8 y subs.m3u8 hasta el último segmento con subtítulo. Devuelve el
primer seq de la ventana (o None).""" primer seq de la ventana (o None)."""
@@ -580,8 +666,9 @@ def main():
ap.add_argument("--beam", type=int, default=1) ap.add_argument("--beam", type=int, default=1)
ap.add_argument("--hold", type=float, default=1.0, help="segundos del borde que no se confirman todavía") ap.add_argument("--hold", type=float, default=1.0, help="segundos del borde que no se confirman todavía")
ap.add_argument("--window", type=int, default=10, help="segmentos en las listas publicadas") ap.add_argument("--window", type=int, default=10, help="segmentos en las listas publicadas")
ap.add_argument("--bandwidth", type=int, default=2600000) # Sin valor, se miden de la señal (ver Master); con valor, quedan fijos.
ap.add_argument("--resolution", default="1280x720") ap.add_argument("--bandwidth", type=int, default=None)
ap.add_argument("--resolution", default=None)
ap.add_argument("--metrics", default=None) ap.add_argument("--metrics", default=None)
ap.add_argument("--en", action="store_true", help="anunciar la pista English (la escribe orbisubs_tr.py)") ap.add_argument("--en", action="store_true", help="anunciar la pista English (la escribe orbisubs_tr.py)")
ap.add_argument("--lang", default="es", choices=sorted(LANG_NAMES), help="idioma del audio") ap.add_argument("--lang", default="es", choices=sorted(LANG_NAMES), help="idioma del audio")
@@ -620,15 +707,9 @@ def main():
procesado = -1 # último seq cuyo audio ya entró al transcriptor procesado = -1 # último seq cuyo audio ya entró al transcriptor
publicado = -1 # último seq con .vtt escrito publicado = -1 # último seq con .vtt escrito
cues = deque(maxlen=400) cues = deque(maxlen=400)
escribir_atomico(os.path.join(a.dir, "master.m3u8"), master = Master(a)
"#EXTM3U\n#EXT-X-VERSION:3\n" master.escribir()
f'#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="{LANG_NAMES[LANG]}",LANGUAGE="{LANG}",' master.arrancar(src)
'DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,URI="subs.m3u8"\n'
+ ('#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="English (automatic)",LANGUAGE="en",'
'DEFAULT=NO,AUTOSELECT=NO,FORCED=NO,URI="en.m3u8"\n' if a.en else "")
+
f'#EXT-X-STREAM-INF:BANDWIDTH={a.bandwidth},RESOLUTION={a.resolution},SUBTITLES="subs"\n'
"video.m3u8\n")
if a.audio_chunks: if a.audio_chunks:
return bucle_trozos(a, motor, tr, met, cola, src, subs_dir) return bucle_trozos(a, motor, tr, met, cola, src, subs_dir)
+7 -1
View File
@@ -473,7 +473,13 @@ function openView(c) {
// los 3 segmentos de hls.js, que es lo que usaba la 076 para que el inglés llegue a tiempo. // los 3 segmentos de hls.js, que es lo que usaba la 076 para que el inglés llegue a tiempo.
// Con hasta 1,1x de velocidad llega al objetivo (hls.js arranca más atrás del HOLD-BACK). // Con hasta 1,1x de velocidad llega al objetivo (hls.js arranca más atrás del HOLD-BACK).
// Con más de 6 segmentos de atraso (después de un corte de la fuente) salta al vivo (083). // Con más de 6 segmentos de atraso (después de un corte de la fuente) salta al vivo (083).
hls = new Hls({ maxLiveSyncPlaybackRate: 1.1, liveMaxLatencyDurationCount: 6 }); // A mano y no con liveMaxLatencyDurationCount: sin liveSyncDurationCount hls.js tira
// "Illegal hls.js config" y no reproduce nada, y con él se pisa el HOLD-BACK (2026-11-19).
hls = new Hls({ maxLiveSyncPlaybackRate: 1.1 });
hls.on(Hls.Events.LEVEL_UPDATED, (ev, d) => {
const td = d.details.targetduration, obj = hls.targetLatency, pos = hls.liveSyncPosition;
if (td && obj && pos && hls.latency > obj + 6 * td) v.currentTime = pos;
});
hls.on(Hls.Events.ERROR, (ev, d) => { if (!d.fatal) return; if (d.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError(); else hls.startLoad(); }); hls.on(Hls.Events.ERROR, (ev, d) => { if (!d.fatal) return; if (d.type === Hls.ErrorTypes.MEDIA_ERROR) hls.recoverMediaError(); else hls.startLoad(); });
hls.loadSource(src); hls.attachMedia(v); hls.loadSource(src); hls.attachMedia(v);
hls.on(Hls.Events.SUBTITLE_TRACKS_UPDATED, () => { hls.on(Hls.Events.SUBTITLE_TRACKS_UPDATED, () => {
+12 -1
View File
@@ -15,6 +15,13 @@
let hls; let hls;
// ?u=/hls/<canal>/master.m3u8 elige el canal (lo usan los enlaces del panel, tarea 079). // ?u=/hls/<canal>/master.m3u8 elige el canal (lo usan los enlaces del panel, tarea 079).
const qu=new URLSearchParams(location.search).get('u'); if(qu&&/^\/hls\/[a-z0-9-]+\/master\.m3u8$/.test(qu)) document.getElementById('u').value=qu; const qu=new URLSearchParams(location.search).get('u'); if(qu&&/^\/hls\/[a-z0-9-]+\/master\.m3u8$/.test(qu)) document.getElementById('u').value=qu;
// Si quedó más de 6 segmentos detrás del colchón (corte largo de la fuente), al vivo.
function saltarAlVivo(h,v){
h.on(Hls.Events.LEVEL_UPDATED,(e,d)=>{
const td=d.details.targetduration, obj=h.targetLatency, pos=h.liveSyncPosition;
if(td&&obj&&pos&&h.latency>obj+6*td) v.currentTime=pos;
});
}
function cargar(){ function cargar(){
const v=document.getElementById('v'), s=document.getElementById('s'); const v=document.getElementById('v'), s=document.getElementById('s');
if(hls) hls.destroy(); if(hls) hls.destroy();
@@ -25,7 +32,11 @@ function cargar(){
// (medido en la 081: objetivo 12 s, quedaba en 18): con hasta 1,1x de velocidad converge. // (medido en la 081: objetivo 12 s, quedaba en 18): con hasta 1,1x de velocidad converge.
// Tras un corte largo de la fuente (CDN de T13, 65 s el 2026-11-17 17:37) el player quedaba // Tras un corte largo de la fuente (CDN de T13, 65 s el 2026-11-17 17:37) el player quedaba
// un minuto atrás y a 1,1x tardaba ~10 min en volver: con más de 6 segmentos de atraso salta al vivo. // un minuto atrás y a 1,1x tardaba ~10 min en volver: con más de 6 segmentos de atraso salta al vivo.
hls=new Hls(sync>0?{liveSyncDuration:sync,liveMaxLatencyDuration:sync+12,maxLiveSyncPlaybackRate:1.1}:{maxLiveSyncPlaybackRate:1.1,liveMaxLatencyDurationCount:6}); // El salto va a mano (saltarAlVivo): liveMaxLatencyDurationCount solo hace que hls.js tire
// "Illegal hls.js config" si no va con liveSyncDurationCount, y ese pisa el HOLD-BACK
// (pasó con 4f7a685: ningún canal reproducía, 2026-11-19).
hls=new Hls(sync>0?{liveSyncDuration:sync,liveMaxLatencyDuration:sync+12,maxLiveSyncPlaybackRate:1.1}:{maxLiveSyncPlaybackRate:1.1});
if(!(sync>0)) saltarAlVivo(hls,v);
// Recuperación estándar de hls.js: el CDN de origen mete cortes de PTS en las tandas // Recuperación estándar de hls.js: el CDN de origen mete cortes de PTS en las tandas
// y el decoder del navegador a veces se cae ahí (visto con Chromium, 2026-11-16). // y el decoder del navegador a veces se cae ahí (visto con Chromium, 2026-11-16).
hls.on(Hls.Events.ERROR,(e,d)=>{ if(!d.fatal) return; hls.on(Hls.Events.ERROR,(e,d)=>{ if(!d.fatal) return;