104b195d38
Mismos segmentos y .vtt que el HLS, retraso fijo configurable (24 s), envío al ritmo del PCR interpolado (las ráfagas tiraban paquetes en UDP). Tarea 078.
650 lines
26 KiB
Python
650 lines
26 KiB
Python
#!/usr/bin/env python3
|
||
"""OrbiSubs SRT — salida MPEG-TS por SRT con los subtítulos dentro del H.264 (tarea 078).
|
||
|
||
- Lee los mismos segmentos que el HLS (<dir>/src/N.ts) y los mismos textos
|
||
(subs/N.vtt en español, en/N.vtt en inglés): no hay otra lectura de la fuente ni
|
||
otros pedidos a gpu02.
|
||
- Mete en cada access unit un SEI GA94 (ATSC A/53) con cc_data:
|
||
608 CC1 (campo 1) = español, 608 CC3 (campo 2) = inglés,
|
||
708 servicio 1 = español, 708 servicio 2 = inglés.
|
||
El H.264 no se recodifica: solo se agrega una NAL SEI antes del primer slice y se
|
||
vuelve a empaquetar el PES. El audio pasa tal cual.
|
||
- Sale con un retraso fijo (--delay) contra la llegada del segmento: lo justo para
|
||
que el texto, sobre todo el inglés, ya esté cuando se arma ese tramo. Si un
|
||
subtítulo no llega a tiempo el video no se frena: el cue sale tarde o se pierde, y
|
||
se cuenta en las métricas.
|
||
|
||
Por qué en Python y no GStreamer: Debian 12 trae GStreamer 1.22, sin gst-plugins-rs
|
||
(tttocea608/tttocea708) y sin h264ccinserter (llegó en 1.26). Compilar todo eso para
|
||
una prueba era más pesado que este encoder, que es chico y no toca el video.
|
||
"""
|
||
import argparse, json, os, socket, subprocess, time, unicodedata
|
||
from collections import deque
|
||
|
||
from orbisubs import log, leer_lista
|
||
|
||
FPS_TICKS = 3000 # 90 kHz / 30 fps
|
||
|
||
|
||
# ---------------------------------------------------------------- texto ------
|
||
|
||
def vtt_cues(path):
|
||
try:
|
||
txt = open(path, encoding="utf-8").read()
|
||
except FileNotFoundError:
|
||
return None
|
||
out, bloque = [], txt.split("\n\n")
|
||
for b in bloque:
|
||
ls = [l for l in b.splitlines() if l.strip()]
|
||
for i, l in enumerate(ls):
|
||
if "-->" in l:
|
||
a, c = [x.strip().split(" ")[0] for x in l.split("-->")]
|
||
out.append((seg_vtt(a), seg_vtt(c), " ".join(ls[i + 1:]).strip()))
|
||
break
|
||
return out
|
||
|
||
|
||
def seg_vtt(s):
|
||
h, m, r = s.split(":")
|
||
return int(h) * 3600 + int(m) * 60 + float(r)
|
||
|
||
|
||
def envolver(txt, ancho=32, max_lineas=4):
|
||
"""608 tiene 32 columnas; se usa el mismo corte en 708 para que se vean igual."""
|
||
lineas, cur = [], ""
|
||
for w in txt.split():
|
||
if cur and len(cur) + 1 + len(w) > ancho:
|
||
lineas.append(cur)
|
||
cur = w
|
||
else:
|
||
cur = f"{cur} {w}".strip()
|
||
if cur:
|
||
lineas.append(cur)
|
||
if len(lineas) > max_lineas:
|
||
lineas = lineas[:max_lineas]
|
||
lineas[-1] = lineas[-1][:ancho - 3] + "..."
|
||
return [l[:ancho] for l in lineas]
|
||
|
||
|
||
# ----------------------------------------------------------------- 608 -------
|
||
|
||
def par(b):
|
||
"""Paridad impar en el bit 7 (608 la exige en cada byte)."""
|
||
b &= 0x7F
|
||
return b | (0x80 if bin(b).count("1") % 2 == 0 else 0)
|
||
|
||
|
||
# Juego básico del 608: ASCII con algunas posiciones cambiadas por letras acentuadas.
|
||
BASICO = {"á": 0x2A, "é": 0x5C, "í": 0x5E, "ó": 0x5F, "ú": 0x60, "ç": 0x7B, "÷": 0x7C, "Ñ": 0x7D, "ñ": 0x7E}
|
||
ASCII_OCUPADO = set("*\\^_`{|}~") # esas posiciones son otras letras en 608
|
||
ESPECIAL = {"®": 0x30, "°": 0x31, "½": 0x32, "¿": 0x33, "™": 0x34, "¢": 0x35, "£": 0x36, "♪": 0x37,
|
||
"à": 0x38, "è": 0x3A, "â": 0x3B, "ê": 0x3C, "î": 0x3D, "ô": 0x3E, "û": 0x3F}
|
||
# Extendidos: van precedidos de un carácter básico de reemplazo (el deco viejo lo
|
||
# muestra; el nuevo lo pisa con el extendido).
|
||
EXT12 = {"Á": 0x20, "É": 0x21, "Ó": 0x22, "Ú": 0x23, "Ü": 0x24, "ü": 0x25, "‘": 0x26, "¡": 0x27, "*": 0x28,
|
||
"’": 0x29, "—": 0x2A, "©": 0x2B, "•": 0x2D, "“": 0x2E, "”": 0x2F, "À": 0x30, "Â": 0x31, "Ç": 0x32,
|
||
"È": 0x33, "Ê": 0x34, "Ë": 0x35, "ë": 0x36, "Î": 0x37, "Ï": 0x38, "ï": 0x39, "Ô": 0x3A, "Ù": 0x3B,
|
||
"ù": 0x3C, "Û": 0x3D, "«": 0x3E, "»": 0x3F}
|
||
EXT13 = {"Ã": 0x20, "ã": 0x21, "Í": 0x22, "Ì": 0x23, "ì": 0x24, "Ò": 0x25, "ò": 0x26, "Õ": 0x27, "õ": 0x28,
|
||
"{": 0x29, "}": 0x2A, "\\": 0x2B, "^": 0x2C, "_": 0x2D, "|": 0x2E, "~": 0x2F, "Ä": 0x30, "ä": 0x31,
|
||
"Ö": 0x32, "ö": 0x33, "ß": 0x34, "¥": 0x35, "¤": 0x36}
|
||
FALLBACK = {"‘": "'", "’": "'", "“": '"', "”": '"', "«": '"', "»": '"', "—": "-", "–": "-", "¡": "!", "…": "...",
|
||
"*": ".", "€": "EUR", "{": "(", "}": ")", "\\": "/", "^": "'", "_": "-", "|": "!", "~": "-", "ß": "s"}
|
||
|
||
|
||
def base_de(ch):
|
||
"""Carácter básico más parecido (para el reemplazo de los extendidos y lo que no existe)."""
|
||
if ch in FALLBACK:
|
||
return FALLBACK[ch]
|
||
d = unicodedata.normalize("NFKD", ch)
|
||
d = "".join(c for c in d if not unicodedata.combining(c))
|
||
return d if d and all(0x20 <= ord(c) < 0x7F and c not in ASCII_OCUPADO for c in d) else "?"
|
||
|
||
|
||
def texto_608(txt):
|
||
"""Lista de 'tokens': ('b', byte) básico o ('c', b1, b2) código de dos bytes."""
|
||
out = []
|
||
for ch in txt:
|
||
if ch in BASICO:
|
||
out.append(("b", BASICO[ch]))
|
||
elif 0x20 <= ord(ch) < 0x7F and ch not in ASCII_OCUPADO:
|
||
out.append(("b", ord(ch)))
|
||
elif ch in ESPECIAL:
|
||
out.append(("c", 0x11, ESPECIAL[ch]))
|
||
elif ch in EXT12 or ch in EXT13:
|
||
for r in base_de(ch)[:1]:
|
||
out.append(("b", BASICO.get(r, ord(r))))
|
||
out.append(("c", 0x12, EXT12[ch]) if ch in EXT12 else ("c", 0x13, EXT13[ch]))
|
||
else:
|
||
for r in base_de(ch):
|
||
out.append(("b", ord(r)))
|
||
return out
|
||
|
||
|
||
PAC_FILA = {12: (0x13, 0x40), 13: (0x13, 0x60), 14: (0x14, 0x40), 15: (0x14, 0x60), 11: (0x10, 0x40)}
|
||
|
||
|
||
class Enc608:
|
||
"""Pop-on: se carga en la memoria no visible mientras se ve el anterior y EOC
|
||
los da vuelta en el PTS del cue. Cada código de control va dos veces (redundancia
|
||
que piden los decos)."""
|
||
|
||
def __init__(self, campo):
|
||
self.misc = 0x14 if campo == 1 else 0x15 # CC1 en campo 1, CC3 en campo 2
|
||
self.cola, self.vistos = [], set()
|
||
self.cargando, self.cargado, self.mostrando = None, None, None
|
||
self.out = deque()
|
||
self.st = {"cues": 0, "tarde": 0, "perdidos": 0, "tarde_max_s": 0.0}
|
||
|
||
def agregar(self, cue, t_actual):
|
||
k = (round(cue[0], 2), cue[2])
|
||
if k in self.vistos:
|
||
return
|
||
self.vistos.add(k)
|
||
if len(self.vistos) > 2000:
|
||
self.vistos = set(list(self.vistos)[-1000:])
|
||
if cue[1] <= t_actual + 0.5:
|
||
self.st["perdidos"] += 1 # llegó cuando ya había pasado
|
||
return
|
||
self.cola.append(cue)
|
||
self.cola.sort()
|
||
|
||
def _carga(self, cue):
|
||
ctl = lambda a, b: [(a, b), (a, b)]
|
||
pares = ctl(self.misc, 0x20) + ctl(self.misc, 0x2E) # RCL, ENM
|
||
lineas = envolver(cue[2])
|
||
fila0 = 16 - len(lineas)
|
||
for i, l in enumerate(lineas):
|
||
ind = (32 - len(l)) // 2
|
||
a, b = PAC_FILA[fila0 + i]
|
||
pares += ctl(a, b + 0x10 + (ind // 4) * 2) # PAC con sangría
|
||
if ind % 4:
|
||
pares += ctl(0x17, 0x20 + ind % 4) # tab offset 1-3
|
||
pend = None
|
||
for tok in texto_608(l):
|
||
if tok[0] == "b":
|
||
if pend is None:
|
||
pend = tok[1]
|
||
else:
|
||
pares.append((pend, tok[1]))
|
||
pend = None
|
||
else:
|
||
if pend is not None:
|
||
pares.append((pend, 0x00)) # cierra con nulo
|
||
pend = None
|
||
pares += ctl(tok[1], tok[2])
|
||
if pend is not None:
|
||
pares.append((pend, 0x00))
|
||
return pares
|
||
|
||
def siguiente(self, t):
|
||
if self.out:
|
||
return self.out.popleft()
|
||
if self.cargado and t >= self.cargado[0]:
|
||
atraso = t - self.cargado[0]
|
||
if atraso > 0.2:
|
||
self.st["tarde"] += 1
|
||
self.st["tarde_max_s"] = max(self.st["tarde_max_s"], round(atraso, 2))
|
||
self.out += [(self.misc, 0x2F), (self.misc, 0x2F)] # EOC
|
||
self.mostrando, self.cargado = self.cargado, None
|
||
self.st["cues"] += 1
|
||
return self.out.popleft()
|
||
if self.mostrando and t >= self.mostrando[1]:
|
||
if not (self.cargado and self.cargado[0] <= self.mostrando[1] + 0.2):
|
||
self.out += [(self.misc, 0x2C), (self.misc, 0x2C)] # EDM
|
||
self.mostrando = None
|
||
if self.out:
|
||
return self.out.popleft()
|
||
if not self.cargando and not self.cargado:
|
||
while self.cola and self.cola[0][1] <= t + 0.5:
|
||
self.cola.pop(0)
|
||
self.st["perdidos"] += 1
|
||
if self.cola:
|
||
cue = self.cola.pop(0)
|
||
self.cargando = [cue, deque(self._carga(cue))]
|
||
if self.cargando:
|
||
p = self.cargando[1].popleft()
|
||
if not self.cargando[1]:
|
||
self.cargado, self.cargando = self.cargando[0], None
|
||
return p
|
||
return (0x00, 0x00)
|
||
|
||
def bytes(self, t):
|
||
a, b = self.siguiente(t)
|
||
return par(a), par(b)
|
||
|
||
|
||
# ----------------------------------------------------------------- 708 -------
|
||
|
||
def texto_708(txt):
|
||
out = bytearray()
|
||
for ch in txt:
|
||
o = ord(ch)
|
||
if 0x20 <= o < 0x7F:
|
||
out.append(o)
|
||
elif ch == "♪":
|
||
out.append(0x7F)
|
||
elif 0xA0 <= o <= 0xFF: # G1 = Latin-1: á é í ó ú ñ ü ¿ ¡ Á É Í Ñ… directo
|
||
out.append(o)
|
||
else:
|
||
out += base_de(ch).encode("ascii", "replace")
|
||
return bytes(out)
|
||
|
||
|
||
class Enc708:
|
||
"""Un servicio 708. Dos ventanas que se alternan: la siguiente se define oculta y
|
||
se llena mientras se ve la actual; en el PTS del cue se muestra y se oculta la otra.
|
||
Los comandos 708 se ejecutan al llegar, así que mostrar/ocultar va en el cuadro justo."""
|
||
|
||
def __init__(self, servicio, presupuesto=14):
|
||
self.svc, self.pres = servicio, presupuesto
|
||
self.cola, self.vistos = [], set()
|
||
self.carga = bytearray() # definición + texto del cue planificado (oculto)
|
||
self.eventos = [] # [t, bytes, es_mostrar] ordenados por t
|
||
self.planificado = None # cue cargándose o cargado, todavía no mostrado
|
||
self.w = 1
|
||
self.st = {"cues": 0, "tarde": 0, "perdidos": 0}
|
||
|
||
agregar = Enc608.agregar
|
||
|
||
def _planificar(self, t):
|
||
if self.planificado or not self.cola:
|
||
return
|
||
while self.cola and self.cola[0][1] <= t + 0.5:
|
||
self.cola.pop(0)
|
||
self.st["perdidos"] += 1
|
||
if not self.cola:
|
||
return
|
||
cue = self.cola.pop(0)
|
||
self.w ^= 1
|
||
w, otra = self.w, self.w ^ 1
|
||
lineas = envolver(cue[2])
|
||
df = bytes([0x98 + w, 0x18, 0x80 | 90, 50, (7 << 4) | (len(lineas) - 1), 31, (1 << 3) | 1])
|
||
self.carga = bytearray(df + bytes([0x88, 1 << w, 0x92, 0, 0]) + b"\x0d".join(texto_708(l) for l in lineas))
|
||
self.eventos.append([cue[0], bytes([0x8A, 1 << otra, 0x89, 1 << w]), True]) # HDW otra + DSW esta
|
||
self.eventos.append([cue[1], bytes([0x8A, 1 << w]), False]) # HDW al terminar
|
||
self.eventos.sort(key=lambda e: e[0])
|
||
self.planificado = cue
|
||
|
||
def bloque(self, t):
|
||
self._planificar(t)
|
||
out = bytearray()
|
||
while self.eventos and self.eventos[0][0] <= t:
|
||
ev = self.eventos[0]
|
||
if ev[2] and self.carga:
|
||
break # no se muestra a medio cargar: sale tarde
|
||
if ev[2]:
|
||
if t - ev[0] > 0.2:
|
||
self.st["tarde"] += 1
|
||
self.st["cues"] += 1
|
||
self.planificado = None
|
||
out += ev[1]
|
||
self.eventos.pop(0)
|
||
libre = self.pres - len(out)
|
||
if libre > 0 and self.carga:
|
||
out += self.carga[:libre]
|
||
del self.carga[:libre]
|
||
return bytes(out)
|
||
|
||
|
||
class DTVCC:
|
||
def __init__(self):
|
||
self.seq = 0
|
||
|
||
def triples(self, bloques, max_pares=18):
|
||
datos = bytearray()
|
||
for svc, b in bloques:
|
||
if b:
|
||
datos += bytes([(svc << 5) | len(b)]) + b
|
||
if not datos:
|
||
return [(0xFA, 0x00, 0x00)] * max_pares
|
||
total = 1 + len(datos)
|
||
if total % 2:
|
||
datos.append(0x00)
|
||
total += 1
|
||
pkt = bytes([(self.seq << 6) | (total // 2)]) + bytes(datos)
|
||
self.seq = (self.seq + 1) % 4
|
||
out = []
|
||
for i in range(0, len(pkt), 2):
|
||
out.append((0xFF if i == 0 else 0xFE, pkt[i], pkt[i + 1])) # tipo 3 inicio, tipo 2 sigue
|
||
out += [(0xFA, 0x00, 0x00)] * (max_pares - len(out))
|
||
return out[:max_pares]
|
||
|
||
|
||
def sei_ga94(triples):
|
||
payload = b"\xb5\x00\x31GA94\x03" + bytes([0x40 | len(triples), 0xFF])
|
||
payload += b"".join(bytes(t) for t in triples) + b"\xff"
|
||
msg = bytes([4])
|
||
n = len(payload)
|
||
while n >= 255:
|
||
msg += b"\xff"
|
||
n -= 255
|
||
msg += bytes([n]) + payload
|
||
rbsp = b"\x06" + msg + b"\x80"
|
||
# Emulation prevention: 00 00 0x (x<=3) → 00 00 03 0x.
|
||
out, ceros = bytearray(), 0
|
||
for b in rbsp:
|
||
if ceros >= 2 and b <= 3:
|
||
out.append(3)
|
||
ceros = 0
|
||
out.append(b)
|
||
ceros = ceros + 1 if b == 0 else 0
|
||
return b"\x00\x00\x00\x01" + bytes(out)
|
||
|
||
|
||
# ------------------------------------------------------------------ TS -------
|
||
|
||
def af_util(af):
|
||
"""Adaptation field sin el relleno (para poder volver a empaquetar)."""
|
||
if not af:
|
||
return b""
|
||
L = af[0]
|
||
if L == 0:
|
||
return b""
|
||
flags = af[1]
|
||
n = 1
|
||
if flags & 0x10: n += 6
|
||
if flags & 0x08: n += 6
|
||
if flags & 0x04: n += 1
|
||
if flags & 0x02: n += 1 + af[1 + n]
|
||
if flags & 0x01: n += 1 + af[1 + n]
|
||
util = af[1:1 + n]
|
||
if flags == 0:
|
||
return b""
|
||
return bytes([len(util)]) + util
|
||
|
||
|
||
def pcr_de(af):
|
||
if af and af[0] >= 7 and af[1] & 0x10:
|
||
b = af[2:8]
|
||
base = (b[0] << 25) | (b[1] << 17) | (b[2] << 9) | (b[3] << 1) | (b[4] >> 7)
|
||
ext = ((b[4] & 1) << 8) | b[5]
|
||
return base * 300 + ext
|
||
return None
|
||
|
||
|
||
def partir(pkt):
|
||
pid = ((pkt[1] & 0x1F) << 8) | pkt[2]
|
||
pusi = bool(pkt[1] & 0x40)
|
||
afc = (pkt[3] >> 4) & 3
|
||
i, af = 4, b""
|
||
if afc & 2:
|
||
af = pkt[4:5 + pkt[4]]
|
||
i = 5 + pkt[4]
|
||
pay = pkt[i:] if afc & 1 else b""
|
||
return pid, pusi, af, pay
|
||
|
||
|
||
def pts_de(pes):
|
||
if pes[7] & 0x80:
|
||
b = pes[9:14]
|
||
return ((b[0] >> 1) & 7) << 30 | b[1] << 22 | (b[2] >> 1) << 15 | b[3] << 7 | b[4] >> 1
|
||
return None
|
||
|
||
|
||
class Remux:
|
||
def __init__(self):
|
||
self.vpid, self.pmt, self.pcr_pid = None, None, None
|
||
self.cc = {}
|
||
|
||
def _pat_pmt(self, pid, pay):
|
||
if pid == 0 and pay:
|
||
s = pay[1 + pay[0]:]
|
||
self.pmt = ((s[10] & 0x1F) << 8) | s[11]
|
||
elif pid == self.pmt and pay:
|
||
s = pay[1 + pay[0]:]
|
||
ln = ((s[1] & 0x0F) << 8) | s[2]
|
||
self.pcr_pid = ((s[8] & 0x1F) << 8) | s[9]
|
||
pil = ((s[10] & 0x0F) << 8) | s[11]
|
||
i = 12 + pil
|
||
while i < 3 + ln - 4:
|
||
st, epid = s[i], ((s[i + 1] & 0x1F) << 8) | s[i + 2]
|
||
if st == 0x1B:
|
||
self.vpid = epid
|
||
i += 5 + (((s[i + 3] & 0x0F) << 8) | s[i + 4])
|
||
|
||
def _pkt(self, pid, pusi, af, pay, prio_bits=0):
|
||
c = self.cc.get(pid, 15)
|
||
if pay:
|
||
c = (c + 1) & 15
|
||
self.cc[pid] = c
|
||
afc = (2 if af else 0) | (1 if pay else 0)
|
||
h = bytes([0x47, (0x40 if pusi else 0) | prio_bits | (pid >> 8), pid & 0xFF, (afc << 4) | c])
|
||
p = h + af + pay
|
||
assert len(p) == 188, len(p)
|
||
return p
|
||
|
||
def _relleno(self, af, pay):
|
||
falta = 184 - len(af) - len(pay)
|
||
if falta <= 0:
|
||
return af
|
||
if af:
|
||
return bytes([af[0] + falta]) + af[1:] + b"\xff" * falta
|
||
if falta == 1:
|
||
return b"\x00"
|
||
return bytes([falta - 1, 0x00]) + b"\xff" * (falta - 2)
|
||
|
||
def segmento(self, data, cc_para):
|
||
"""Devuelve [(paquete, pcr|None)] con el SEI metido en cada PES de video.
|
||
cc_para(lista_pts) -> {pts: triples} se llama con todos los PTS del segmento."""
|
||
pkts = [data[i:i + 188] for i in range(0, len(data) - 187, 188) if data[i] == 0x47]
|
||
grupos, cur = [], None
|
||
for p in pkts:
|
||
pid, pusi, af, pay = partir(p)
|
||
if pid in (0, self.pmt):
|
||
self._pat_pmt(pid, pay)
|
||
if pid == self.vpid:
|
||
if pusi:
|
||
cur = [p]
|
||
grupos.append(("v", cur))
|
||
elif cur is not None:
|
||
cur.append(p)
|
||
else:
|
||
grupos.append(("o", p))
|
||
else:
|
||
grupos.append(("o", p))
|
||
# PTS de cada PES (orden de decodificación) → cc en orden de presentación.
|
||
lista = []
|
||
for k, g in grupos:
|
||
if k == "v":
|
||
pes = partir(g[0])[3]
|
||
lista.append(pts_de(pes))
|
||
mapa = cc_para([x for x in lista if x is not None])
|
||
out = []
|
||
for k, g in grupos:
|
||
if k == "o":
|
||
pid, pusi, af, pay = partir(g)
|
||
out.append((self._pkt(pid, pusi, af, pay, g[1] & 0x20), pcr_de(af) if pid == self.pcr_pid else None))
|
||
continue
|
||
partes = [partir(p) for p in g]
|
||
pes = b"".join(x[3] for x in partes)
|
||
pts = pts_de(pes)
|
||
hdr = 9 + pes[8]
|
||
es = pes[hdr:]
|
||
sei = sei_ga94(mapa[pts]) if pts in mapa else b""
|
||
if sei:
|
||
j = 0
|
||
while True:
|
||
j = es.find(b"\x00\x00\x01", j)
|
||
if j < 0 or j + 3 >= len(es):
|
||
j = -1
|
||
break
|
||
if es[j + 3] & 0x1F in (1, 5):
|
||
break
|
||
j += 3
|
||
if j >= 0:
|
||
if j > 0 and es[j - 1] == 0:
|
||
j -= 1
|
||
es = es[:j] + sei + es[j:]
|
||
plen = (pes[4] << 8) | pes[5]
|
||
nuevo_pes = bytearray(pes[:hdr]) + es
|
||
if plen:
|
||
nl = len(nuevo_pes) - 6
|
||
nuevo_pes[4:6] = (nl if nl <= 0xFFFF else 0).to_bytes(2, "big")
|
||
nuevo_pes = bytes(nuevo_pes)
|
||
pos = 0
|
||
for i, (pid, pusi, af, pay) in enumerate(partes):
|
||
afu = af_util(af)
|
||
cap = 184 - len(afu)
|
||
trozo = nuevo_pes[pos:pos + cap]
|
||
pos += len(trozo)
|
||
ultimo = pos >= len(nuevo_pes)
|
||
afx = self._relleno(afu, trozo) if len(trozo) < cap else afu
|
||
out.append((self._pkt(pid, i == 0, afx, trozo, g[i][1] & 0x20), pcr_de(afu) if pid == self.pcr_pid else None))
|
||
if ultimo:
|
||
break
|
||
while pos < len(nuevo_pes):
|
||
# Lo que el SEI corrió para adelante va en paquetes nuevos (el último con relleno).
|
||
trozo = nuevo_pes[pos:pos + 184]
|
||
pos += len(trozo)
|
||
afx = self._relleno(b"", trozo) if len(trozo) < 184 else b""
|
||
out.append((self._pkt(self.vpid, False, afx, trozo), None))
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------- main -------
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--dir", required=True)
|
||
ap.add_argument("--delay", type=float, default=20.0, help="segundos de retraso fijo contra la llegada del segmento")
|
||
ap.add_argument("--port", type=int, default=9000, help="SRT listener para clientes")
|
||
ap.add_argument("--port-test", type=int, default=9001, help="SRT listener para el HLS de prueba interno")
|
||
ap.add_argument("--metrics", default=None)
|
||
a = ap.parse_args()
|
||
|
||
# srt-live-transmit acepta un solo cliente por listener: uno para afuera y otro
|
||
# para la prueba interna (HLS con -c copy, como OrbiOrigin).
|
||
hijos = {}
|
||
|
||
def vigilar():
|
||
for i, (srt_p, udp_p) in enumerate([(a.port, 19000), (a.port_test, 19001)]):
|
||
p = hijos.get(i)
|
||
if p is None or p.poll() is not None:
|
||
if p is not None:
|
||
log("srt_child_restart", port=srt_p, rc=p.returncode)
|
||
hijos[i] = subprocess.Popen(["srt-live-transmit", "-q", f"udp://127.0.0.1:{udp_p}?rcvbuf=8388608",
|
||
f"srt://:{srt_p}?mode=listener&latency=200"],
|
||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||
vigilar()
|
||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||
destinos = [("127.0.0.1", 19000), ("127.0.0.1", 19001)]
|
||
|
||
es608, en608 = Enc608(1), Enc608(2)
|
||
es708, en708 = Enc708(1), Enc708(2)
|
||
dtv = DTVCC()
|
||
rmx = Remux()
|
||
met = open(a.metrics, "a") if a.metrics else None
|
||
src = os.path.join(a.dir, "src", "index.m3u8")
|
||
|
||
llegada, siguiente = {}, None
|
||
t_ult = 0.0 # PTS (s) del último cuadro ya armado: lo que empiece antes llegó tarde
|
||
base_wall, base_pcr, ultimo_pcr = None, None, None
|
||
while True:
|
||
segs, _ = leer_lista(src)
|
||
ahora = time.time()
|
||
for s in segs:
|
||
if s[0] not in llegada:
|
||
# Llegada = cuando ffmpeg cerró el .ts (mtime), no cuando lo vimos: si no,
|
||
# los segmentos que ya estaban al arrancar salían todos juntos en ráfaga.
|
||
try:
|
||
llegada[s[0]] = os.path.getmtime(os.path.join(a.dir, "src", s[1]))
|
||
except FileNotFoundError:
|
||
llegada[s[0]] = ahora
|
||
for k in [k for k in llegada if segs and k < segs[0][0] - 5]:
|
||
llegada.pop(k)
|
||
if siguiente is None and segs:
|
||
siguiente = segs[-1][0]
|
||
cand = [s for s in segs if s[0] == siguiente]
|
||
if not cand:
|
||
if segs and siguiente < segs[0][0]:
|
||
siguiente = segs[0][0] # se quedó atrás de la lista: saltar
|
||
vigilar()
|
||
time.sleep(0.2)
|
||
continue
|
||
seq, uri, dur, _ = cand[0]
|
||
listo = llegada[seq] + a.delay
|
||
if base_wall is not None:
|
||
listo = max(listo - dur, time.time()) # se arma un segmento antes de que toque
|
||
while time.time() < listo:
|
||
time.sleep(0.05)
|
||
try:
|
||
data = open(os.path.join(a.dir, "src", uri), "rb").read()
|
||
except FileNotFoundError:
|
||
siguiente += 1
|
||
continue
|
||
|
||
# Textos disponibles ahora (los mismos .vtt que usa el HLS).
|
||
for k in range(seq - 4, seq + 6):
|
||
for path, encs in ((f"subs/{k}.vtt", (es608, es708)), (f"en/{k}.vtt", (en608, en708))):
|
||
cues = vtt_cues(os.path.join(a.dir, path))
|
||
for c in cues or []:
|
||
for e in encs:
|
||
e.agregar(c, t_ult)
|
||
|
||
def cc_para(lista):
|
||
nonlocal_t[0] = max(lista) / 90000.0 if lista else nonlocal_t[0]
|
||
orden = sorted(set(lista))
|
||
mapa = {}
|
||
for p in orden:
|
||
t = p / 90000.0
|
||
f1 = es608.bytes(t)
|
||
f2 = en608.bytes(t)
|
||
tri = [(0xFC, f1[0], f1[1]), (0xFD, f2[0], f2[1])]
|
||
tri += dtv.triples([(1, es708.bloque(t)), (2, en708.bloque(t))])
|
||
mapa[p] = tri
|
||
return mapa
|
||
|
||
nonlocal_t = [t_ult]
|
||
a0 = time.time()
|
||
pkts = rmx.segmento(data, cc_para)
|
||
t_ult = nonlocal_t[0]
|
||
prep = time.time() - a0
|
||
# Envío al ritmo del PCR. El primer segmento fija la base; si el PCR salta (la
|
||
# ingesta reinició) se vuelve a fijar.
|
||
pcrs = [(i, p) for i, (_, p) in enumerate(pkts) if p is not None]
|
||
if not pcrs:
|
||
siguiente += 1
|
||
continue
|
||
p0 = pcrs[0][1]
|
||
if base_wall is None or ultimo_pcr is None or abs((p0 - ultimo_pcr) / 27e6) > 10:
|
||
base_wall, base_pcr = max(time.time(), llegada[seq] + a.delay), p0
|
||
log("srt_base", seq=seq)
|
||
atraso_envio = time.time() - (base_wall + (p0 - base_pcr) / 27e6)
|
||
# Cada paquete sale en su hora interpolada entre el PCR anterior y el siguiente.
|
||
# Antes salía en ráfaga todo lo que había entre dos PCR (un I-frame entero) y el
|
||
# buffer UDP de srt-live-transmit (212 KB) tiraba paquetes: "Packet corrupt" en
|
||
# el HLS de prueba y PIPELINE_ERROR_DECODE en Chromium (2026-11-16).
|
||
horas = [None] * len(pkts)
|
||
for (ia, pa), (ib, pb) in zip(pcrs, pcrs[1:]):
|
||
for k in range(ia, ib):
|
||
horas[k] = pa + (pb - pa) * (k - ia) / (ib - ia)
|
||
ia, pa = pcrs[-1]
|
||
tasa = (pcrs[-1][1] - pcrs[0][1]) / max(1, pcrs[-1][0] - pcrs[0][0]) # ticks por paquete
|
||
for k in range(ia, len(pkts)):
|
||
horas[k] = pa + tasa * (k - ia)
|
||
for k in range(0, pcrs[0][0]):
|
||
horas[k] = pcrs[0][1]
|
||
for k in range(0, len(pkts), 7):
|
||
objetivo = base_wall + (horas[k] - base_pcr) / 27e6
|
||
espera = objetivo - time.time()
|
||
if espera > 0:
|
||
time.sleep(espera)
|
||
trozo = b"".join(p for p, _ in pkts[k:k + 7])
|
||
for d in destinos:
|
||
sock.sendto(trozo, d)
|
||
ultimo_pcr = pcrs[-1][1]
|
||
vigilar()
|
||
m = {"t": round(time.time(), 2), "seq": seq, "prep_s": round(prep, 3), "pkts": len(pkts),
|
||
"atraso_envio_s": round(atraso_envio, 2), "retraso_fijo_s": a.delay,
|
||
"es608": dict(es608.st), "en608": dict(en608.st), "es708": dict(es708.st), "en708": dict(en708.st)}
|
||
log("srt_segment", **m)
|
||
if met:
|
||
met.write(json.dumps(m) + "\n")
|
||
met.flush()
|
||
siguiente += 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|