OrbiSubs panel: start/stop via systemd, per-channel SRT output, T13 as a panel channel

El panel genera /etc/orbisubs/<id>.env, arranca o para las instancias y mira 12 s
que queden andando; si no, vuelve a lo anterior. Salida SRT por canal (listener o
caller, latency, passphrase, CC1/CC3 y servicios 708, UDP internos puerto+10000).
Ingesta numerada con la hora: al reiniciar, la secuencia volvía a 0 y el ASR se
trababa. Tope de 2 canales andando (gpu02) y throttle de arranques. Tarea 079.
This commit is contained in:
guy
2026-11-16 23:59:59 -03:00
parent 78f6aa8668
commit 742627428a
18 changed files with 451 additions and 46 deletions
+26
View File
@@ -68,6 +68,32 @@ systemctl start orbisubs-srthls@t13 # opcional: HLS de prueba en /hls/t13-c
ffprobe srt://<ip>:9000 # Video: h264 ..., Closed Captions ffprobe srt://<ip>:9000 # Video: h264 ..., Closed Captions
``` ```
## Panel web (tarea 079)
`panel/`: Node + Express + better-sqlite3, mismo estilo que OrbiStream (copia de
`styles.css`, `orbi-lang.js`, `node-foot.js` y `url-parse.js`). Da de alta y edita
canales, los inicia y los para con las instancias systemd de arriba, y muestra el estado
real (systemd + métricas de `/var/log/orbisubs`), el player y los últimos subtítulos.
- **URL:** `http://<ip>:4700/`. Login `admin`/`admin` con cambio obligatorio al entrar.
`tools/reset-admin.js` vuelve la cuenta a admin/admin.
- **Aplicar:** al iniciar, o al guardar un canal que está andando, escribe
`/etc/orbisubs/<id>.env` (atómico) y hace `restart` de sus instancias. Después mira
12 s: si alguna no queda activa o se reinicia, vuelve al `.env` anterior y muestra
el error del proceso. Un `.env` hecho a mano se guarda en `<id>.env.antes-panel`.
- **Topes:** 2 canales andando a la vez (gpu02) y 5 arranques por canal en 10 min.
Validación de id repetido, puertos repetidos (la salida SRT toma puerto, puerto+1 y
los UDP internos puerto+10000/+10001) y URL de entrada, en la API y en el modal.
```bash
# Node 22 propio (Debian 12 trae 18; better-sqlite3 12 pide >= 20)
tar xf node-v22.*-linux-x64.tar.xz -C /opt/node --strip-components=1
cp -r panel/{package.json,package-lock.json,src,tools} /opt/orbisubs-panel/
cd /opt/orbisubs-panel && /opt/node/bin/npm ci --omit=dev
cp deploy/orbisubs-panel.service /etc/systemd/system/
systemctl daemon-reload && systemctl enable --now orbisubs-panel
```
## Archivos ## Archivos
| Archivo | Qué es | | Archivo | Qué es |
+3
View File
@@ -1,6 +1,9 @@
[Unit] [Unit]
Description=OrbiSubs transcripción %i (faster-whisper → WebVTT) Description=OrbiSubs transcripción %i (faster-whisper → WebVTT)
After=orbisubs-ingest@%i.service After=orbisubs-ingest@%i.service
# Throttle: como mucho 5 arranques en 10 min (caso TVR-hls de v1: loops de restarts).
StartLimitIntervalSec=600
StartLimitBurst=5
[Service] [Service]
EnvironmentFile=/etc/orbisubs/%i.env EnvironmentFile=/etc/orbisubs/%i.env
+3
View File
@@ -1,6 +1,9 @@
[Unit] [Unit]
Description=OrbiSubs ingesta %i (ffmpeg -c copy a HLS) Description=OrbiSubs ingesta %i (ffmpeg -c copy a HLS)
After=network-online.target After=network-online.target
# Throttle: como mucho 5 arranques en 10 min (caso TVR-hls de v1: loops de restarts).
StartLimitIntervalSec=600
StartLimitBurst=5
[Service] [Service]
EnvironmentFile=/etc/orbisubs/%i.env EnvironmentFile=/etc/orbisubs/%i.env
+1 -1
View File
@@ -9,7 +9,7 @@ StartLimitBurst=5
EnvironmentFile=/etc/orbisubs/%i.env EnvironmentFile=/etc/orbisubs/%i.env
ExecStartPre=/bin/mkdir -p /var/log/orbisubs ExecStartPre=/bin/mkdir -p /var/log/orbisubs
ExecStart=/opt/orbisubs/venv/bin/python /opt/orbisubs/orbisubs_srt.py --dir /var/www/hls/%i \ ExecStart=/opt/orbisubs/venv/bin/python /opt/orbisubs/orbisubs_srt.py --dir /var/www/hls/%i \
--delay ${SRT_DELAY} --port ${SRT_PORT} --port-test ${SRT_PORT_TEST} --metrics /var/log/orbisubs/%i-srt.jsonl --delay ${SRT_DELAY} --port ${SRT_PORT} --port-test ${SRT_PORT_TEST} --metrics /var/log/orbisubs/%i-srt.jsonl $SRT_EXTRA
Restart=always Restart=always
RestartSec=10 RestartSec=10
+6
View File
@@ -1,6 +1,9 @@
[Unit] [Unit]
Description=OrbiSubs prueba: HLS con -c copy desde la salida SRT %i (como OrbiOrigin) Description=OrbiSubs prueba: HLS con -c copy desde la salida SRT %i (como OrbiOrigin)
After=orbisubs-srt@%i.service After=orbisubs-srt@%i.service
# Throttle: como mucho 5 arranques en 10 min (caso TVR-hls de v1: loops de restarts).
StartLimitIntervalSec=600
StartLimitBurst=5
[Service] [Service]
EnvironmentFile=/etc/orbisubs/%i.env EnvironmentFile=/etc/orbisubs/%i.env
@@ -10,3 +13,6 @@ ExecStart=/usr/bin/ffmpeg -hide_banner -loglevel warning -nostdin -i "srt://127.
-hls_segment_filename /var/www/hls/%i-cc/%%d.ts /var/www/hls/%i-cc/index.m3u8 -hls_segment_filename /var/www/hls/%i-cc/%%d.ts /var/www/hls/%i-cc/index.m3u8
Restart=always Restart=always
RestartSec=5 RestartSec=5
[Install]
WantedBy=multi-user.target
+3
View File
@@ -1,6 +1,9 @@
[Unit] [Unit]
Description=OrbiSubs traducción %i (español → inglés con el LLM de gpu02) Description=OrbiSubs traducción %i (español → inglés con el LLM de gpu02)
After=orbisubs-asr@%i.service After=orbisubs-asr@%i.service
# Throttle: como mucho 5 arranques en 10 min (caso TVR-hls de v1: loops de restarts).
StartLimitIntervalSec=600
StartLimitBurst=5
[Service] [Service]
EnvironmentFile=/etc/orbisubs/%i.env EnvironmentFile=/etc/orbisubs/%i.env
+10 -2
View File
@@ -6,16 +6,24 @@
# ~20 s (2026-11-16). aresample async rellena los huecos para que el PTS siga. El audio a 16 kHz lo saca orbisubs.py de cada segmento: # ~20 s (2026-11-16). aresample async rellena los huecos para que el PTS siga. El audio a 16 kHz lo saca orbisubs.py de cada segmento:
# así el texto queda atado al PTS del mismo .ts que ve el player. # así el texto queda atado al PTS del mismo .ts que ve el player.
# Uso: ingest.sh <canal> <url-entrada> (config en /etc/orbisubs/<canal>.env) # Uso: ingest.sh <canal> <url-entrada> (config en /etc/orbisubs/<canal>.env)
# MAP_VIDEO / MAP_AUDIO (panel, tarea 079): programa o PID de audio cuando la fuente
# trae más de uno (p. ej. 0:p:2:v y 0:i:0x101). Por defecto, el primero de cada uno.
set -eu set -eu
CANAL="$1"; IN="$2" CANAL="$1"; IN="$2"
DIR="/var/www/hls/$CANAL/src" DIR="/var/www/hls/$CANAL/src"
mkdir -p "$DIR" mkdir -p "$DIR"
# Numeración que nunca vuelve atrás: con -start_number 0, al reiniciar la ingesta los
# segmentos volvían a 0 y orbisubs.py se quedaba esperando el siguiente al último viejo
# (T13 trabado sin subtítulos al reiniciarlo desde el panel, tarea 079, 2026-11-17).
# Con la hora en segundos, el primero nuevo siempre es mayor que el último viejo
# (avanza 1 por segmento de varios segundos), y los demás procesos ya saben saltar.
rm -f "$DIR"/*.ts "$DIR"/index.m3u8
EXTRA=() EXTRA=()
# HLS de un CDN público: algunos piden User-Agent de navegador. # HLS de un CDN público: algunos piden User-Agent de navegador.
case "$IN" in http*) EXTRA=(-user_agent "Mozilla/5.0" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5);; esac case "$IN" in http*) EXTRA=(-user_agent "Mozilla/5.0" -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5);; esac
exec ffmpeg -hide_banner -loglevel warning -nostdin "${EXTRA[@]}" -i "$IN" \ exec ffmpeg -hide_banner -loglevel warning -nostdin "${EXTRA[@]}" -i "$IN" \
-map 0:v:0 -map 0:a:0 -c:v copy \ -map "${MAP_VIDEO:-0:v:0}" -map "${MAP_AUDIO:-0:a:0}" -c:v copy \
-c:a aac -b:a 128k -ar 48000 -ac 2 -af aresample=async=1000 \ -c:a aac -b:a 128k -ar 48000 -ac 2 -af aresample=async=1000 \
-f hls -hls_time "${HLS_TIME:-6}" -hls_list_size 20 \ -f hls -hls_time "${HLS_TIME:-6}" -hls_list_size 20 \
-hls_flags delete_segments+program_date_time+temp_file+independent_segments \ -hls_flags delete_segments+program_date_time+temp_file+independent_segments \
-hls_segment_filename "$DIR/%d.ts" "$DIR/index.m3u8" -start_number "$(date +%s)" -hls_segment_filename "$DIR/%d.ts" "$DIR/index.m3u8"
+18 -3
View File
@@ -30,6 +30,10 @@ WRAP = 2 ** 33 / 90000.0
# whisper soltaba una frase sin puntos, se autoalimentaba: a los minutos todo salía # whisper soltaba una frase sin puntos, se autoalimentaba: a los minutos todo salía
# en minúsculas y sin puntuación (T13, 2026-11-16), y el traductor no podía cortar frases. # en minúsculas y sin puntuación (T13, 2026-11-16), y el traductor no podía cortar frases.
PROMPT = "Hola, buenas noches. Estas son las noticias de T13, en Santiago de Chile." PROMPT = "Hola, buenas noches. Estas son las noticias de T13, en Santiago de Chile."
# Idioma del audio y prompt por canal (los define el panel, tarea 079). El prompt va
# por entorno (ASR_PROMPT) porque systemd parte $ASR_EXTRA en los espacios.
LANG = "es"
LANG_NAMES = {"es": "Español (automático)", "en": "English (automatic)", "pt": "Português (automático)"}
def log(msg, **kw): def log(msg, **kw):
@@ -96,7 +100,7 @@ class MotorLocal:
self.beam = beam self.beam = beam
def __call__(self, audio, prompt): def __call__(self, audio, prompt):
segs, _ = self.m.transcribe(audio, language="es", beam_size=self.beam, word_timestamps=True, segs, _ = self.m.transcribe(audio, language=LANG, beam_size=self.beam, word_timestamps=True,
vad_filter=True, vad_parameters={"min_silence_duration_ms": 500}, vad_filter=True, vad_parameters={"min_silence_duration_ms": 500},
condition_on_previous_text=False, initial_prompt=prompt) condition_on_previous_text=False, initial_prompt=prompt)
return [(w.start, w.end, w.word) for s in segs for w in (s.words or [])] return [(w.start, w.end, w.word) for s in segs for w in (s.words or [])]
@@ -120,7 +124,7 @@ class MotorHTTP:
b = io.BytesIO() b = io.BytesIO()
with wave.open(b, "wb") as w: with wave.open(b, "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR); w.writeframes(pcm) w.setnchannels(1); w.setsampwidth(2); w.setframerate(SR); w.writeframes(pcm)
data = {"temperature": "0.0", "response_format": "verbose_json", "language": "es"} data = {"temperature": "0.0", "response_format": "verbose_json", "language": LANG}
if prompt: if prompt:
data["prompt"] = prompt data["prompt"] = prompt
t = time.time() t = time.time()
@@ -241,6 +245,7 @@ def escribir_atomico(path, txt):
def main(): def main():
global LANG, PROMPT
ap = argparse.ArgumentParser() ap = argparse.ArgumentParser()
ap.add_argument("--dir", required=True, help="carpeta del canal; ffmpeg escribe en <dir>/src/index.m3u8") ap.add_argument("--dir", required=True, help="carpeta del canal; ffmpeg escribe en <dir>/src/index.m3u8")
ap.add_argument("--engine", default="http", choices=["http", "local"]) ap.add_argument("--engine", default="http", choices=["http", "local"])
@@ -256,7 +261,10 @@ def main():
ap.add_argument("--resolution", default="1280x720") ap.add_argument("--resolution", default="1280x720")
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("--prompt", default=os.environ.get("ASR_PROMPT") or PROMPT)
a = ap.parse_args() a = ap.parse_args()
LANG, PROMPT = a.lang, a.prompt
t = time.time() t = time.time()
if a.engine == "http": if a.engine == "http":
@@ -281,7 +289,7 @@ def main():
cues = deque(maxlen=400) cues = deque(maxlen=400)
escribir_atomico(os.path.join(a.dir, "master.m3u8"), escribir_atomico(os.path.join(a.dir, "master.m3u8"),
"#EXTM3U\n#EXT-X-VERSION:3\n" "#EXTM3U\n#EXT-X-VERSION:3\n"
'#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="Español (automático)",LANGUAGE="es",' 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' 'DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,URI="subs.m3u8"\n'
+ ('#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="English (automatic)",LANGUAGE="en",' + ('#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 "") 'DEFAULT=NO,AUTOSELECT=NO,FORCED=NO,URI="en.m3u8"\n' if a.en else "")
@@ -294,6 +302,13 @@ def main():
ahora = time.time() ahora = time.time()
for seq, uri, dur, pdt in segs: for seq, uri, dur, pdt in segs:
llegada.setdefault(seq, ahora) llegada.setdefault(seq, ahora)
if segs and segs[-1][0] < procesado:
# La lista volvió atrás (ingesta reiniciada con numeración vieja): empezar de nuevo.
log("sequence_reset", last=procesado, now=segs[-1][0])
procesado = -1
info.clear()
llegada.clear()
llegada.update((x[0], ahora) for x in segs)
nuevos = [s for s in segs if s[0] > procesado] nuevos = [s for s in segs if s[0] > procesado]
if not nuevos: if not nuevos:
time.sleep(0.2) time.sleep(0.2)
+42 -11
View File
@@ -511,27 +511,54 @@ def main():
ap.add_argument("--port", type=int, default=9000, help="SRT listener para clientes") 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("--port-test", type=int, default=9001, help="SRT listener para el HLS de prueba interno")
ap.add_argument("--metrics", default=None) ap.add_argument("--metrics", default=None)
# Lo que se define por canal desde el panel (tarea 079). Los valores por defecto
# son los de la 078: listener, CC1 = idioma del audio, CC3 = inglés, 708 servicios 1 y 2.
ap.add_argument("--mode", default="listener", choices=["listener", "caller"])
ap.add_argument("--host", default="", help="destino en modo caller")
ap.add_argument("--latency", type=int, default=200, help="latency SRT (ms)")
ap.add_argument("--passphrase", default="")
ap.add_argument("--udp-base", type=int, default=0,
help="puertos UDP internos hacia srt-live-transmit (base y base+1); 0 = puerto + 10000")
ap.add_argument("--cc608-main", default="CC1", choices=["CC1", "CC3", "-"])
ap.add_argument("--cc608-en", default="CC3", choices=["CC1", "CC3", "-"])
ap.add_argument("--svc-main", type=int, default=1, help="servicio 708 del idioma del audio (0 = no va)")
ap.add_argument("--svc-en", type=int, default=2, help="servicio 708 del inglés (0 = no va)")
a = ap.parse_args() a = ap.parse_args()
# srt-live-transmit acepta un solo cliente por listener: uno para afuera y otro # srt-live-transmit acepta un solo cliente por listener: uno para afuera y otro
# para la prueba interna (HLS con -c copy, como OrbiOrigin). # para la prueba interna (HLS con -c copy, como OrbiOrigin). Los UDP internos
# salen del puerto del canal: con 19000/19001 fijos, dos canales chocaban.
base = a.udp_base or a.port + 10000
qs = f"latency={a.latency}" + (f"&passphrase={a.passphrase}" if a.passphrase else "")
salidas = [(f"srt://{a.host}:{a.port}?mode=caller&{qs}" if a.mode == "caller"
else f"srt://:{a.port}?mode=listener&{qs}", base)]
if a.port_test:
salidas.append((f"srt://:{a.port_test}?mode=listener&latency=200", base + 1))
hijos = {} hijos = {}
def vigilar(): def vigilar():
for i, (srt_p, udp_p) in enumerate([(a.port, 19000), (a.port_test, 19001)]): for i, (url, udp_p) in enumerate(salidas):
p = hijos.get(i) p = hijos.get(i)
if p is None or p.poll() is not None: if p is None or p.poll() is not None:
if p is not None: if p is not None:
log("srt_child_restart", port=srt_p, rc=p.returncode) log("srt_child_restart", url=url.split("passphrase=")[0], rc=p.returncode)
hijos[i] = subprocess.Popen(["srt-live-transmit", "-q", f"udp://127.0.0.1:{udp_p}?rcvbuf=8388608", hijos[i] = subprocess.Popen(["srt-live-transmit", "-q", f"udp://127.0.0.1:{udp_p}?rcvbuf=8388608", url],
f"srt://:{srt_p}?mode=listener&latency=200"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
vigilar() vigilar()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
destinos = [("127.0.0.1", 19000), ("127.0.0.1", 19001)] destinos = [("127.0.0.1", udp) for _, udp in salidas]
es608, en608 = Enc608(1), Enc608(2) # 608: el campo 1 lleva CC1 y el campo 2 lleva CC3. Cada idioma va al campo que
es708, en708 = Enc708(1), Enc708(2) # diga el panel; un codificador sin idioma solo manda relleno.
campo = {1: Enc608(1), 2: Enc608(2)}
es608 = campo[2] if a.cc608_main == "CC3" else campo[1]
en608 = campo[1] if a.cc608_en == "CC1" else campo[2]
sin_608 = Enc608(1) # sumidero para un idioma que no va en 608
if a.cc608_main == "-":
es608 = sin_608
if a.cc608_en == "-":
en608 = sin_608
es708, en708 = Enc708(a.svc_main or 1), Enc708(a.svc_en or 2)
dtv = DTVCC() dtv = DTVCC()
rmx = Remux() rmx = Remux()
met = open(a.metrics, "a") if a.metrics else None met = open(a.metrics, "a") if a.metrics else None
@@ -588,10 +615,14 @@ def main():
mapa = {} mapa = {}
for p in orden: for p in orden:
t = p / 90000.0 t = p / 90000.0
f1 = es608.bytes(t) f1 = campo[1].bytes(t)
f2 = en608.bytes(t) f2 = campo[2].bytes(t)
if sin_608 is es608 or sin_608 is en608:
sin_608.bytes(t) # avanza igual, para que no se le acumule la cola
tri = [(0xFC, f1[0], f1[1]), (0xFD, f2[0], f2[1])] tri = [(0xFC, f1[0], f1[1]), (0xFD, f2[0], f2[1])]
tri += dtv.triples([(1, es708.bloque(t)), (2, en708.bloque(t))]) # bloque() se llama siempre (avanza el codificador); sin servicio, no se manda.
b708 = [(a.svc_main, es708.bloque(t)), (a.svc_en, en708.bloque(t))]
tri += dtv.triples([(sv, b) for sv, b in b708 if sv])
mapa[p] = tri mapa[p] = tri
return mapa return mapa
+171
View File
@@ -0,0 +1,171 @@
'use strict';
// apply.js — lleva un canal del panel a las instancias systemd que ya existen
// (orbisubs-ingest@, -asr@, -tr@, -srt@, -srthls@): escribe /etc/orbisubs/<id>.env
// y las arranca o las para. Si algo no arranca, vuelve al .env anterior y lo dice:
// guardar no deja un canal a medias.
const fs = require('fs');
const path = require('path');
const { execFile } = require('child_process');
const status = require('./status');
const ETC = process.env.ORBISUBS_ETC || '/etc/orbisubs';
const CHECK_S = Number(process.env.APPLY_CHECK_S || 12); // cuánto mirar después de arrancar
function sh(cmd, args, timeout = 30000) {
return new Promise(resolve => {
execFile(cmd, args, { timeout }, (err, stdout, stderr) => resolve({ ok: !err, out: String(stdout || ''), err: String(stderr || (err && err.message) || '') }));
});
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
// URL de entrada para ffmpeg. Ojo: en ffmpeg la latency de SRT va en MICROsegundos
// (el mismo error que url-parse.js documenta para OrbiStream: 2000 → 2 ms).
function inputUrl(i) {
if (i.kind !== 'srt') return i.url;
const q = [`mode=${i.mode}`, `latency=${i.latency_ms * 1000}`];
if (i.streamid) q.push(`streamid=${encodeURIComponent(i.streamid)}`);
if (i.passphrase) q.push(`passphrase=${encodeURIComponent(i.passphrase)}`);
return `srt://${i.mode === 'listener' ? '0.0.0.0' : i.host}:${i.port}?${q.join('&')}`;
}
const q = v => `"${String(v).replace(/[\\"]/g, '\\$&')}"`;
function envText(ch) {
const c = ch.cfg;
const asrExtra = [`--lang ${c.asr.lang}`, `--window ${c.hls.list_size}`];
if (c.tr.langs.includes('en')) asrExtra.unshift('--en');
const lines = [
`# /etc/orbisubs/${ch.slug}.env — lo genera el panel de OrbiSubs (${new Date().toISOString()}).`,
'# No editar a mano: se pisa cada vez que se guarda o se inicia el canal desde el panel.',
`INPUT=${q(inputUrl(c.input))}`,
`HLS_TIME=${c.hls.seg_s}`,
`MAP_VIDEO=${c.input.program ? `0:p:${c.input.program}:v` : '0:v:0'}`,
`MAP_AUDIO=${c.input.audio_pid ? `0:i:${c.input.audio_pid}` : (c.input.program ? `0:p:${c.input.program}:a` : '0:a:0')}`,
'ENGINE=http',
`URL=${q(c.asr.url)}`,
// Solo los usa engine=local (faster-whisper); el ExecStart del asr los pide igual.
'MODEL=small', 'DEVICE=cpu', 'COMPUTE=int8', 'THREADS=4', 'BEAM=1',
`ASR_EXTRA=${q(asrExtra.join(' '))}`,
`ASR_PROMPT=${q(c.asr.prompt || '')}`,
`LLM_URL=${q(c.tr.url)}`,
`LLM_MODEL=${q(c.tr.model || 'qwen2.5-7b-instruct')}`,
];
if (c.srt.enabled) {
const s = c.srt;
const extra = [`--mode ${s.mode}`, `--latency ${s.latency_ms}`,
`--cc608-main ${s.cc608[c.asr.lang] || '-'}`, `--cc608-en ${s.cc608.en || '-'}`,
`--svc-main ${s.cc708[c.asr.lang] || 0}`, `--svc-en ${s.cc708.en || 0}`];
if (s.mode === 'caller') extra.push(`--host ${s.host}`);
if (s.passphrase) extra.push(`--passphrase ${s.passphrase}`);
lines.push(`SRT_DELAY=${s.delay_s}`, `SRT_PORT=${s.port}`,
`SRT_PORT_TEST=${s.mode === 'listener' && s.test ? s.port + 1 : 0}`, `SRT_EXTRA=${q(extra.join(' '))}`);
}
return lines.join('\n') + '\n';
}
// Instancias que el canal tiene que tener andando según su configuración.
function wanted(ch) {
const u = status.unitsOf(ch).map(x => x.unit);
if (ch.cfg.srt.enabled && ch.cfg.srt.mode === 'listener' && ch.cfg.srt.test) u.push(`orbisubs-srthls@${ch.slug}.service`);
return u;
}
const ALL_KINDS = ['ingest', 'asr', 'tr', 'srt', 'srthls'];
const allUnits = slug => ALL_KINDS.map(k => `orbisubs-${k}@${slug}.service`);
function writeEnv(slug, text) {
const file = path.join(ETC, `${slug}.env`);
fs.mkdirSync(ETC, { recursive: true });
let prev = null;
try { prev = fs.readFileSync(file, 'utf8'); } catch { /* canal nuevo */ }
// Un .env armado a mano (T13 de la 076-078) se guarda la primera vez que lo pisa el panel.
if (prev !== null && !prev.includes('lo genera el panel') && !fs.existsSync(`${file}.antes-panel`)) {
fs.writeFileSync(`${file}.antes-panel`, prev, { mode: 0o640 });
}
const tmp = `${file}.tmp-${process.pid}`;
fs.writeFileSync(tmp, text, { mode: 0o640 });
fs.renameSync(tmp, file); // atómico: un servicio que arranca justo nunca lee medio archivo
return prev;
}
function restoreEnv(slug, prev) {
const file = path.join(ETC, `${slug}.env`);
if (prev === null) { try { fs.unlinkSync(file); } catch { /* ya no está */ } return; }
fs.writeFileSync(`${file}.tmp-${process.pid}`, prev, { mode: 0o640 });
fs.renameSync(`${file}.tmp-${process.pid}`, file);
}
// Lo último que dijo el proceso (no systemd: "Started…", "Scheduled restart…" no explican nada).
async function journalTail(unit) {
const r = await sh('journalctl', ['-u', unit, '-n', '30', '-o', 'json', '--no-pager', '-q']);
const lines = [];
for (const l of r.out.split('\n')) {
try { const j = JSON.parse(l); if (j._PID !== '1' && j.MESSAGE) lines.push(String(j.MESSAGE)); } catch { /* línea vacía */ }
}
return (lines.slice(-2).join(' | ') || 'sin mensajes del proceso').slice(0, 400);
}
// Mira las instancias unos segundos: tienen que quedar activas y sin reinicios nuevos.
async function verify(units) {
const before = await status.systemdState(units);
const deadline = Date.now() + CHECK_S * 1000;
let st = before;
while (Date.now() < deadline) {
await sleep(1500);
st = await status.systemdState(units);
const bad = units.filter(u => st[u] && (st[u].active === 'failed' || st[u].restarts > (before[u] ? before[u].restarts : 0)));
if (bad.length) break;
}
const errors = [];
for (const u of units) {
const s = st[u] || {};
const restarted = s.restarts > (before[u] ? before[u].restarts : 0);
if (s.active !== 'active' || restarted) {
errors.push(`${u.replace(/\.service$/, '')}: ${s.active || '?'}${s.result && s.result !== 'success' ? ` (${s.result})` : ''}${restarted ? ', se reinició' : ''} — ${await journalTail(u)}`);
}
}
return errors;
}
async function stopUnits(units) {
if (!units.length) return;
await sh('systemctl', ['disable', '--now', ...units], 60000);
await sh('systemctl', ['reset-failed', ...units]);
}
// Arranca (o re-aplica) el canal. Devuelve {ok, errors}.
async function start(ch, { prevCh = null } = {}) {
const units = wanted(ch);
const extra = allUnits(ch.slug).filter(u => !units.includes(u));
const prev = writeEnv(ch.slug, envText(ch));
await stopUnits(extra); // p. ej. se apagó la traducción
await sh('systemctl', ['reset-failed', ...units]);
// restart (no start): si ya andaba, toma el .env nuevo.
const r = await sh('systemctl', ['restart', ...units], 60000);
if (ch.enabled) await sh('systemctl', ['enable', ...units]);
let errors = r.ok ? await verify(units) : [`systemctl restart: ${r.err.trim().slice(0, 300)}`];
if (!errors.length) return { ok: true, errors: [] };
// No quedó andando: se vuelve a lo anterior para no dejarlo a medias.
if (prevCh && prev !== null) {
restoreEnv(ch.slug, prev);
const pu = wanted(prevCh);
await stopUnits(allUnits(ch.slug).filter(u => !pu.includes(u)));
await sh('systemctl', ['reset-failed', ...pu]);
await sh('systemctl', ['restart', ...pu], 60000);
errors.push('Se volvió a la configuración anterior del canal.');
} else {
await stopUnits(allUnits(ch.slug));
restoreEnv(ch.slug, prev);
errors.push('El canal quedó parado.');
}
return { ok: false, errors };
}
async function stop(ch) {
await stopUnits(allUnits(ch.slug));
return { ok: true };
}
function removeEnv(slug) {
try { fs.unlinkSync(path.join(ETC, `${slug}.env`)); } catch { /* no estaba */ }
}
module.exports = { start, stop, envText, inputUrl, wanted, allUnits, removeEnv };
+15 -5
View File
@@ -9,7 +9,8 @@
const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,30}$/; const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;
// Puertos del CT que no puede tomar ningún canal (ssh, smtp local, nginx, este panel). // Puertos del CT que no puede tomar ningún canal (ssh, smtp local, nginx, este panel).
const RESERVED = new Set([22, 25, 80, 443, Number(process.env.PORT) || 4700]); const RESERVED = new Set([22, 25, 80, 443, Number(process.env.PORT) || 4700]);
const CC608 = ['CC1', 'CC2', 'CC3', 'CC4']; // El codificador de la 078 escribe CC1 (campo 1) y CC3 (campo 2); CC2/CC4 no.
const CC608 = ['CC1', 'CC3'];
const LANGS = ['es', 'en', 'pt']; const LANGS = ['es', 'en', 'pt'];
class ValidationError extends Error { class ValidationError extends Error {
@@ -47,6 +48,8 @@ function host(v, field, label) {
function passphrase(v, field) { function passphrase(v, field) {
const s = str(v); const s = str(v);
if (s && (s.length < 10 || s.length > 79)) bad('La passphrase SRT tiene que tener entre 10 y 79 caracteres', field); if (s && (s.length < 10 || s.length > 79)) bad('La passphrase SRT tiene que tener entre 10 y 79 caracteres', field);
// Va en una URL y en la línea de comando del servicio: sin espacios ni caracteres de URL.
if (s && !/^[A-Za-z0-9._~!*+,;:@%-]+$/.test(s)) bad('La passphrase SRT no puede tener espacios, comillas, &, ?, # ni /', field);
return s; return s;
} }
@@ -63,7 +66,7 @@ function input(i = {}) {
passphrase: passphrase(i.passphrase, 'in_passphrase'), passphrase: passphrase(i.passphrase, 'in_passphrase'),
}; };
if (out.streamid.length > 512 || /[\s&]/.test(out.streamid)) bad('streamid: sin espacios ni &, hasta 512 caracteres', 'in_streamid'); if (out.streamid.length > 512 || /[\s&]/.test(out.streamid)) bad('streamid: sin espacios ni &, hasta 512 caracteres', 'in_streamid');
if (mode === 'listener' && RESERVED.has(out.port)) bad(`El puerto ${out.port} lo usa el sistema`, 'in_port'); if (mode === 'listener' && (RESERVED.has(out.port) || out.port < 1024)) bad(`El puerto ${out.port} lo usa el sistema`, 'in_port');
return Object.assign(out, avPick(i)); return Object.assign(out, avPick(i));
} }
if (kind === 'udp') { if (kind === 'udp') {
@@ -121,18 +124,22 @@ function channel(body = {}) {
}, },
srt: { enabled: !!srt.enabled }, srt: { enabled: !!srt.enabled },
}; };
if (cfg.tr.langs.length && cfg.asr.lang === 'en') bad('El audio ya es inglés: no hace falta traducir a inglés', 'tr_langs'); // El traductor (orbisubs_tr.py) está armado para español de Chile → inglés.
if (cfg.tr.langs.length && cfg.asr.lang !== 'es') bad('Por ahora la traducción es solo de español a inglés', 'tr_en');
if (cfg.srt.enabled) { if (cfg.srt.enabled) {
const mode = str(srt.mode) === 'caller' ? 'caller' : 'listener'; const mode = str(srt.mode) === 'caller' ? 'caller' : 'listener';
Object.assign(cfg.srt, { Object.assign(cfg.srt, {
mode, mode,
host: mode === 'caller' ? host(srt.host, 'srt_host', 'Destino de la salida SRT') : '', host: mode === 'caller' ? host(srt.host, 'srt_host', 'Destino de la salida SRT') : '',
port: int(srt.port, 'srt_port', 1024, 65534, 'Puerto de la salida SRT'), // Hasta 55000: los UDP internos hacia srt-live-transmit van en puerto + 10000.
port: int(srt.port, 'srt_port', 1024, 55000, 'Puerto de la salida SRT'),
latency_ms: int(srt.latency_ms === '' || srt.latency_ms == null ? 200 : srt.latency_ms, 'srt_latency', 20, 8000, 'Latency de la salida (ms)'), latency_ms: int(srt.latency_ms === '' || srt.latency_ms == null ? 200 : srt.latency_ms, 'srt_latency', 20, 8000, 'Latency de la salida (ms)'),
passphrase: passphrase(srt.passphrase, 'srt_passphrase'), passphrase: passphrase(srt.passphrase, 'srt_passphrase'),
delay_s: num(srt.delay_s ?? 24, 'srt_delay', 5, 60, 'Retraso fijo del video (s)'), delay_s: num(srt.delay_s ?? 24, 'srt_delay', 5, 60, 'Retraso fijo del video (s)'),
cc608: {}, cc708: {}, cc608: {}, cc708: {},
// HLS de prueba con -c copy desde la salida SRT (/hls/<id>-cc/, como OrbiOrigin; 078).
test: !!srt.test,
}); });
// Qué idioma va en cada canal 608 y servicio 708. Vacío = ese idioma no va. // Qué idioma va en cada canal 608 y servicio 708. Vacío = ese idioma no va.
const langsOut = [cfg.asr.lang, ...cfg.tr.langs]; const langsOut = [cfg.asr.lang, ...cfg.tr.langs];
@@ -140,7 +147,7 @@ function channel(body = {}) {
for (const l of langsOut) { for (const l of langsOut) {
const v608 = str((srt.cc608 || {})[l]); const v608 = str((srt.cc608 || {})[l]);
if (v608) { if (v608) {
if (!CC608.includes(v608)) bad(`608 de ${l}: CC1 a CC4`, 'srt_cc608'); if (!CC608.includes(v608)) bad(`608 de ${l}: CC1 o CC3`, 'srt_cc608');
if (used608.has(v608)) bad(`${v608} está repetido entre idiomas`, 'srt_cc608'); if (used608.has(v608)) bad(`${v608} está repetido entre idiomas`, 'srt_cc608');
used608.add(v608); cfg.srt.cc608[l] = v608; used608.add(v608); cfg.srt.cc608[l] = v608;
} }
@@ -167,6 +174,9 @@ function portsOf(cfg) {
if (cfg.srt && cfg.srt.enabled && cfg.srt.mode === 'listener') { if (cfg.srt && cfg.srt.enabled && cfg.srt.mode === 'listener') {
out.push({ port: cfg.srt.port, what: 'salida SRT' }, { port: cfg.srt.port + 1, what: 'prueba interna de la salida SRT' }); out.push({ port: cfg.srt.port, what: 'salida SRT' }, { port: cfg.srt.port + 1, what: 'prueba interna de la salida SRT' });
} }
if (cfg.srt && cfg.srt.enabled) {
out.push({ port: cfg.srt.port + 10000, what: 'UDP interno de la salida SRT' }, { port: cfg.srt.port + 10001, what: 'UDP interno de la salida SRT' });
}
return out; return out;
} }
+30 -6
View File
@@ -8,6 +8,16 @@ const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<':
const MEDIA = `${location.protocol}//${location.hostname}`; const MEDIA = `${location.protocol}//${location.hostname}`;
let me = null, channels = [], control = false, controlMsg = ''; let me = null, channels = [], control = false, controlMsg = '';
const pending = new Set();
let noticeTimer = null;
function notice(msg, isErr) {
const el = $('#notice');
el.textContent = msg || '';
el.classList.toggle('hidden', !msg);
el.classList.toggle('err', !!isErr);
clearTimeout(noticeTimer);
if (msg) noticeTimer = setTimeout(() => el.classList.add('hidden'), 30000);
}
let pollTimer = null; let pollTimer = null;
OrbiLang.apply(document); OrbiLang.apply(document);
@@ -134,8 +144,9 @@ function renderChannels() {
const offTitle = control ? '' : ` — ${t(controlMsg)}`; const offTitle = control ? '' : ` — ${t(controlMsg)}`;
$('#tbl-channels tbody').innerHTML = channels.map(c => { $('#tbl-channels tbody').innerHTML = channels.map(c => {
const st = c.status || {}; const st = c.status || {};
const [cls, label] = STATE[st.state] || STATE.stopped; const [cls, label] = pending.has(c.id) || c.busy ? STATE.connecting : (STATE[st.state] || STATE.stopped);
const m = st.metrics || {}; // Parado: los números del último rato ya no dicen nada.
const m = st.state === 'stopped' ? { last: (st.metrics || {}).last } : (st.metrics || {});
const lastLines = Object.entries(m.last || {}).map(([l, txt]) => `<div class="ch-sub"><span class="chip">${l}</span> ${esc(txt)}</div>`).join(''); const lastLines = Object.entries(m.last || {}).map(([l, txt]) => `<div class="ch-sub"><span class="chip">${l}</span> ${esc(txt)}</div>`).join('');
const notes = (st.notes || []).join(' · '); const notes = (st.notes || []).join(' · ');
return `<tr data-id="${c.id}"> return `<tr data-id="${c.id}">
@@ -169,7 +180,11 @@ $('#tbl-channels').addEventListener('click', async e => {
try { await api('DELETE', `/api/channels/${c.id}`); loadChannels(); } catch (err) { alert(err.message); } try { await api('DELETE', `/api/channels/${c.id}`); loadChannels(); } catch (err) { alert(err.message); }
return; return;
} }
try { await api('POST', `/api/channels/${c.id}/${act}`); loadChannels(); } catch (err) { alert(err.message); } // Iniciar tarda unos segundos: el backend espera a ver que las instancias queden andando.
pending.add(c.id); renderChannels();
try { await api('POST', `/api/channels/${c.id}/${act}`); notice(''); }
catch (err) { notice(err.message, true); }
finally { pending.delete(c.id); loadChannels(); }
}); });
/* ---------------- Modal alta / edición ---------------- */ /* ---------------- Modal alta / edición ---------------- */
@@ -177,7 +192,7 @@ let editing = null;
const F = () => $('#channel-form'); const F = () => $('#channel-form');
function fillCC() { function fillCC() {
const f = F(); const f = F();
const o608 = ['', 'CC1', 'CC2', 'CC3', 'CC4'].map(v => `<option value="${v}">${v || t('(no va)')}</option>`).join(''); const o608 = ['', 'CC1', 'CC3'].map(v => `<option value="${v}">${v || t('(no va)')}</option>`).join('');
const o708 = ['', 1, 2, 3, 4, 5, 6].map(v => `<option value="${v}">${v || t('(no va)')}</option>`).join(''); const o708 = ['', 1, 2, 3, 4, 5, 6].map(v => `<option value="${v}">${v || t('(no va)')}</option>`).join('');
f.cc608_main.innerHTML = o608; f.cc608_en.innerHTML = o608; f.cc608_main.innerHTML = o608; f.cc608_en.innerHTML = o608;
f.cc708_main.innerHTML = o708; f.cc708_en.innerHTML = o708; f.cc708_main.innerHTML = o708; f.cc708_en.innerHTML = o708;
@@ -227,6 +242,7 @@ function openModal(c) {
f.srt_latency.value = s.latency_ms ?? 200; f.srt_latency.value = s.latency_ms ?? 200;
f.srt_passphrase.value = s.passphrase || ''; f.srt_passphrase.value = s.passphrase || '';
f.srt_delay.value = s.delay_s ?? 24; f.srt_delay.value = s.delay_s ?? 24;
f.srt_test.checked = !!s.test;
const cc608 = s.cc608 || { es: 'CC1', en: 'CC3' }, cc708 = s.cc708 || { es: 1, en: 2 }; const cc608 = s.cc608 || { es: 'CC1', en: 'CC3' }, cc708 = s.cc708 || { es: 1, en: 2 };
f.cc608_main.value = cc608[d.asr.lang] || ''; f.cc608_en.value = cc608.en || ''; f.cc608_main.value = cc608[d.asr.lang] || ''; f.cc608_en.value = cc608.en || '';
f.cc708_main.value = cc708[d.asr.lang] ?? ''; f.cc708_en.value = cc708.en ?? ''; f.cc708_main.value = cc708[d.asr.lang] ?? ''; f.cc708_en.value = cc708.en ?? '';
@@ -256,6 +272,7 @@ function syncForm() {
f.in_url.placeholder = k === 'hls' ? 'https://cdn.ejemplo/canal/playlist.m3u8' : 'udp://@239.1.1.1:5000'; f.in_url.placeholder = k === 'hls' ? 'https://cdn.ejemplo/canal/playlist.m3u8' : 'udp://@239.1.1.1:5000';
$$('.srt-on').forEach(x => x.classList.toggle('hidden', !f.srt_enabled.checked)); $$('.srt-on').forEach(x => x.classList.toggle('hidden', !f.srt_enabled.checked));
$$('.srt-caller').forEach(x => x.classList.toggle('hidden', !f.srt_enabled.checked || f.srt_mode.value !== 'caller')); $$('.srt-caller').forEach(x => x.classList.toggle('hidden', !f.srt_enabled.checked || f.srt_mode.value !== 'caller'));
$$('.srt-listener').forEach(x => x.classList.toggle('hidden', !f.srt_enabled.checked || f.srt_mode.value !== 'listener'));
f.cc608_en.disabled = f.cc708_en.disabled = !f.tr_en.checked; f.cc608_en.disabled = f.cc708_en.disabled = !f.tr_en.checked;
const slug = f.slug.value.trim() || '<id>'; const slug = f.slug.value.trim() || '<id>';
$('#hls-urls').innerHTML = f.hls_enabled.checked $('#hls-urls').innerHTML = f.hls_enabled.checked
@@ -274,6 +291,7 @@ document.addEventListener('click', e => {
}); });
F().addEventListener('input', syncForm); F().addEventListener('input', syncForm);
F().addEventListener('change', syncForm); F().addEventListener('change', syncForm);
$('#btn-new-channel').onclick = () => openModal(null);
$('#modal-close').onclick = $('#btn-cancel').onclick = () => $('#modal').classList.add('hidden'); $('#modal-close').onclick = $('#btn-cancel').onclick = () => $('#modal').classList.add('hidden');
// Pegado rápido: el parser de OrbiStream (url-parse.js) reparte la URL en los campos. // Pegado rápido: el parser de OrbiStream (url-parse.js) reparte la URL en los campos.
@@ -327,7 +345,8 @@ function collect() {
tr: { langs: f.tr_en.checked ? ['en'] : [], url: f.tr_url.value.trim(), model: editing ? editing.cfg.tr.model : undefined }, tr: { langs: f.tr_en.checked ? ['en'] : [], url: f.tr_url.value.trim(), model: editing ? editing.cfg.tr.model : undefined },
hls: { enabled: f.hls_enabled.checked, seg_s: f.hls_seg.value, list_size: f.hls_list.value }, hls: { enabled: f.hls_enabled.checked, seg_s: f.hls_seg.value, list_size: f.hls_list.value },
srt: { enabled: f.srt_enabled.checked, mode: f.srt_mode.value, host: f.srt_host.value.trim(), port: f.srt_port.value, srt: { enabled: f.srt_enabled.checked, mode: f.srt_mode.value, host: f.srt_host.value.trim(), port: f.srt_port.value,
latency_ms: f.srt_latency.value, passphrase: f.srt_passphrase.value.trim(), delay_s: f.srt_delay.value, cc608, cc708 }, latency_ms: f.srt_latency.value, passphrase: f.srt_passphrase.value.trim(), delay_s: f.srt_delay.value, cc608, cc708,
test: f.srt_test.checked },
}, },
}; };
} }
@@ -350,6 +369,8 @@ function checkLocal(b) {
const o = others.find(c => usedPorts(c.cfg).includes(p)); const o = others.find(c => usedPorts(c.cfg).includes(p));
if (o) return [field, t('El puerto {p} ya lo usa el canal "{n}"', { p, n: o.name })]; if (o) return [field, t('El puerto {p} ya lo usa el canal "{n}"', { p, n: o.name })];
} }
if (b.cfg.tr.langs.length && b.cfg.asr.lang !== 'es') return ['tr_en', t('Por ahora la traducción es solo de español a inglés')];
if (b.cfg.srt.enabled && !(Number(b.cfg.srt.port) >= 1024 && Number(b.cfg.srt.port) <= 55000)) return ['srt_port', t('Puerto de la salida SRT: entre 1024 y 55000')];
if (!b.cfg.hls.enabled && !b.cfg.srt.enabled) return ['hls_enabled', t('El canal necesita al menos una salida (HLS o SRT)')]; if (!b.cfg.hls.enabled && !b.cfg.srt.enabled) return ['hls_enabled', t('El canal necesita al menos una salida (HLS o SRT)')];
return null; return null;
} }
@@ -366,13 +387,15 @@ F().addEventListener('submit', async e => {
const bad = checkLocal(b); const bad = checkLocal(b);
if (bad) return showFormError(bad[0], bad[1]); if (bad) return showFormError(bad[0], bad[1]);
$('#btn-save').disabled = true; $('#btn-save').disabled = true;
const up = editing && editing.status && editing.status.state !== 'stopped';
if (up) $('#btn-save').textContent = t('Guardando y reiniciando…');
try { try {
if (editing) await api('PUT', `/api/channels/${editing.id}`, b); if (editing) await api('PUT', `/api/channels/${editing.id}`, b);
else await api('POST', '/api/channels', b); else await api('POST', '/api/channels', b);
$('#modal').classList.add('hidden'); $('#modal').classList.add('hidden');
loadChannels(); loadChannels();
} catch (err) { showFormError(err.field, err.message); } } catch (err) { showFormError(err.field, err.message); }
finally { $('#btn-save').disabled = false; } finally { $('#btn-save').disabled = false; $('#btn-save').textContent = t('Guardar canal'); }
}); });
/* ---------------- Ver canal ---------------- */ /* ---------------- Ver canal ---------------- */
@@ -404,6 +427,7 @@ function openView(c) {
urls.push(c.cfg.srt.mode === 'listener' urls.push(c.cfg.srt.mode === 'listener'
? urlLine(t('Salida SRT'), `srt://${location.hostname}:${c.cfg.srt.port}`) ? urlLine(t('Salida SRT'), `srt://${location.hostname}:${c.cfg.srt.port}`)
: urlLine(t('Salida SRT (caller a)'), `srt://${c.cfg.srt.host}:${c.cfg.srt.port}`)); : urlLine(t('Salida SRT (caller a)'), `srt://${c.cfg.srt.host}:${c.cfg.srt.port}`));
if (c.cfg.srt.test && c.cfg.srt.mode === 'listener') urls.push(urlLine(t('HLS desde la salida SRT (608)'), `${MEDIA}/hls/${c.slug}-cc/index.m3u8`));
} }
$('#view-urls').innerHTML = urls.join(''); $('#view-urls').innerHTML = urls.join('');
loadView(); loadView();
+7 -2
View File
@@ -109,7 +109,6 @@ OrbiLang.add({ en: {
'Listener (los clientes marcan acá)': 'Listener (clients call here)', 'Listener (los clientes marcan acá)': 'Listener (clients call here)',
'Caller (marca a un destino)': 'Caller (calls a destination)', 'Caller (marca a un destino)': 'Caller (calls a destination)',
'Destino (host)': 'Destination (host)', 'Destino (host)': 'Destination (host)',
'En listener toma también el siguiente (prueba interna).': 'As listener it also takes the next one (internal test).',
'Retraso fijo del video (s)': 'Fixed video delay (s)', 'Retraso fijo del video (s)': 'Fixed video delay (s)',
'Lo justo para que el subtítulo (y el inglés, que llega después) caiga a tiempo.': 'Just enough for the subtitle (and the English one, which comes later) to land on time.', 'Lo justo para que el subtítulo (y el inglés, que llega después) caiga a tiempo.': 'Just enough for the subtitle (and the English one, which comes later) to land on time.',
'608 (idioma del audio / inglés)': '608 (audio language / English)', '608 (idioma del audio / inglés)': '608 (audio language / English)',
@@ -140,7 +139,13 @@ OrbiLang.add({ en: {
'perdidos': 'lost', 'perdidos': 'lost',
'sin métricas': 'no metrics', 'sin métricas': 'no metrics',
'sin subtítulos todavía': 'no subtitles yet', 'sin subtítulos todavía': 'no subtitles yet',
'Spanish': 'Spanish', 'Guardando y reiniciando…': 'Saving and restarting…',
'Por ahora la traducción es solo de español a inglés': 'For now translation is only from Spanish to English',
'Puerto de la salida SRT: entre 1024 y 55000': 'SRT output port: between 1024 and 55000',
'Hasta 55000. En listener toma también el siguiente (prueba interna).': 'Up to 55000. As listener it also takes the next one (internal test).',
'Prueba interna: HLS con -c copy desde la salida SRT (/hls/<id>-cc/, como OrbiOrigin)': 'Internal test: HLS with -c copy from the SRT output (/hls/<id>-cc/, like OrbiOrigin)',
'La salida SRT se arma con los mismos segmentos: apagar la salida HLS solo deja de anunciarla en el panel.': 'The SRT output is built from the same segments: turning the HLS output off only stops listing it in the panel.',
'HLS desde la salida SRT (608)': 'HLS from the SRT output (608)',
// ---- Eventos ---- // ---- Eventos ----
'Últimos 200 eventos del panel': 'Last 200 panel events', 'Últimos 200 eventos del panel': 'Last 200 panel events',
'Fecha': 'Date', 'Fecha': 'Date',
+4 -1
View File
@@ -74,6 +74,7 @@
<main class="main"> <main class="main">
<div id="control-banner" class="info-banner hidden"></div> <div id="control-banner" class="info-banner hidden"></div>
<div id="notice" class="info-banner notice hidden" role="status"></div>
<!-- ================= CANALES ================= --> <!-- ================= CANALES ================= -->
<section id="view-channels" class="view"> <section id="view-channels" class="view">
<header class="view-head"> <header class="view-head">
@@ -216,6 +217,7 @@
<label><span data-i18n>Largo de segmento (s)</span> <input name="hls_seg" type="number" min="2" max="10" value="6"></label> <label><span data-i18n>Largo de segmento (s)</span> <input name="hls_seg" type="number" min="2" max="10" value="6"></label>
<label><span data-i18n>Segmentos en la lista</span> <input name="hls_list" type="number" min="3" max="30" value="10"></label> <label><span data-i18n>Segmentos en la lista</span> <input name="hls_list" type="number" min="3" max="30" value="10"></label>
</div> </div>
<p class="field-hint" data-i18n>La salida SRT se arma con los mismos segmentos: apagar la salida HLS solo deja de anunciarla en el panel.</p>
<div class="url-box" id="hls-urls"></div> <div class="url-box" id="hls-urls"></div>
</fieldset> </fieldset>
@@ -233,7 +235,7 @@
</div> </div>
<div class="grid-3 srt-on"> <div class="grid-3 srt-on">
<label><span data-i18n>Puerto</span> <input name="srt_port" type="number" min="1024" max="65534" placeholder="9002"> <label><span data-i18n>Puerto</span> <input name="srt_port" type="number" min="1024" max="65534" placeholder="9002">
<span class="field-hint" data-i18n>En listener toma también el siguiente (prueba interna).</span> <span class="field-hint" data-i18n>Hasta 55000. En listener toma también el siguiente (prueba interna).</span>
</label> </label>
<label>Latency (ms) <input name="srt_latency" type="number" min="20" max="8000" step="10" value="200"></label> <label>Latency (ms) <input name="srt_latency" type="number" min="20" max="8000" step="10" value="200"></label>
<label>Passphrase <input name="srt_passphrase" autocomplete="off" placeholder="(opcional)" data-i18n="placeholder"></label> <label>Passphrase <input name="srt_passphrase" autocomplete="off" placeholder="(opcional)" data-i18n="placeholder"></label>
@@ -249,6 +251,7 @@
<span class="pair"><select name="cc708_main"></select><select name="cc708_en"></select></span> <span class="pair"><select name="cc708_main"></select><select name="cc708_en"></select></span>
</label> </label>
</div> </div>
<label class="chk-wrap srt-on srt-listener"><input type="checkbox" name="srt_test"> <span data-i18n>Prueba interna: HLS con -c copy desde la salida SRT (/hls/&lt;id&gt;-cc/, como OrbiOrigin)</span></label>
<div class="url-box srt-on" id="srt-url"></div> <div class="url-box srt-on" id="srt-url"></div>
</fieldset> </fieldset>
+2
View File
@@ -27,3 +27,5 @@ label.inline select{width:auto}
.sub-list{list-style:none;font-size:13px;line-height:1.45;max-height:210px;overflow-y:auto} .sub-list{list-style:none;font-size:13px;line-height:1.45;max-height:210px;overflow-y:auto}
.sub-list li{padding:4px 0;border-bottom:1px solid var(--border)} .sub-list li{padding:4px 0;border-bottom:1px solid var(--border)}
.sub-list li:first-child{color:var(--amber)} .sub-list li:first-child{color:var(--amber)}
.notice{white-space:pre-wrap}
.notice.err{background:rgba(232,85,85,.12);border-color:var(--red);color:#ffb4b4}
+92 -15
View File
@@ -6,10 +6,11 @@ const { db, event } = require('../db');
const V = require('../engine/validate'); const V = require('../engine/validate');
const status = require('../engine/status'); const status = require('../engine/status');
// Iniciar y parar desde el panel: apagado hasta cerrar la 078 (la otra sesión está const apply = require('../engine/apply');
// trabajando sobre las mismas instancias systemd del CT 176). Ver ~/tareas/079-paralelo.md.
const CONTROL = process.env.ORBISUBS_CONTROL === '1'; // Como máximo 2 canales andando a la vez: el reconocimiento y la traducción van a
const CONTROL_OFF_MSG = 'Iniciar y parar: disponible al cerrar la 078'; // gpu02, que es compartido (076-agregado: ~1 s de whisper por segmento de 6 s).
const MAX_RUNNING = Number(process.env.MAX_RUNNING || 2);
const router = express.Router(); const router = express.Router();
const row2ch = r => ({ id: r.id, slug: r.slug, name: r.name, enabled: !!r.enabled, cfg: JSON.parse(r.cfg), created_at: r.created_at, updated_at: r.updated_at }); const row2ch = r => ({ id: r.id, slug: r.slug, name: r.name, enabled: !!r.enabled, cfg: JSON.parse(r.cfg), created_at: r.created_at, updated_at: r.updated_at });
@@ -24,9 +25,33 @@ function fail(res, e) {
router.get('/', async (req, res) => { router.get('/', async (req, res) => {
const chs = allChannels(); const chs = allChannels();
const st = await status.all(chs); const st = await status.all(chs);
res.json({ control: CONTROL, control_msg: CONTROL ? null : CONTROL_OFF_MSG, channels: chs.map(c => ({ ...c, status: st[c.id] })) }); res.json({ control: true, max_running: MAX_RUNNING, channels: chs.map(c => ({ ...c, status: st[c.id], busy: busy.has(c.id) })) });
}); });
// Una operación a la vez por canal, y como mucho 5 arranques en 10 min (el mismo
// throttle que las unidades systemd; caso TVR-hls de v1: 15k restarts por un loop).
const busy = new Set();
const starts = new Map();
function throttled(id) {
const now = Date.now();
const l = (starts.get(id) || []).filter(t => now - t < 600000);
starts.set(id, l);
if (l.length >= 5) return true;
l.push(now);
return false;
}
// ¿Tiene alguna instancia andando (o arrancando)?
async function isUp(ch) {
const sd = await status.systemdState(apply.allUnits(ch.slug));
return Object.values(sd).some(u => u.active === 'active' || u.active === 'activating' || u.active === 'reloading');
}
async function runningOthers(ch) {
const others = allChannels().filter(o => o.id !== ch.id);
const out = [];
for (const o of others) if (await isUp(o)) out.push(o.name);
return out;
}
router.get('/:id', (req, res) => { router.get('/:id', (req, res) => {
const ch = getChannel(req.params.id); const ch = getChannel(req.params.id);
if (!ch) return res.status(404).json({ error: 'Canal inexistente' }); if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
@@ -68,9 +93,27 @@ router.put('/:id', async (req, res) => {
return res.status(409).json({ error: 'Detén el canal antes de cambiarle el id corto', field: 'slug' }); return res.status(409).json({ error: 'Detén el canal antes de cambiarle el id corto', field: 'slug' });
} }
} }
db.prepare("UPDATE channels SET slug = ?, name = ?, enabled = ?, cfg = ?, updated_at = datetime('now') WHERE id = ?") if (busy.has(old.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
.run(ch.slug, ch.name, ch.enabled ? 1 : 0, JSON.stringify(ch.cfg), old.id); const save = c => db.prepare("UPDATE channels SET slug = ?, name = ?, enabled = ?, cfg = ?, updated_at = datetime('now') WHERE id = ?")
event('info', `Canal editado: ${ch.name}`, { channel: ch.slug, username: req.user.username }); .run(c.slug, c.name, c.enabled ? 1 : 0, JSON.stringify(c.cfg), old.id);
save(ch);
// Andando: se aplica ya. Si no arranca con lo nuevo, vuelve todo (servicios y base)
// a lo anterior, para no dejar el canal a medias.
if (await isUp(old)) {
if (throttled(old.id)) { save(old); return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' }); }
busy.add(old.id);
try {
const r = await apply.start({ ...ch, id: old.id }, { prevCh: old });
if (!r.ok) {
save(old);
event('error', `No se pudo aplicar la edición de ${ch.name}: ${r.errors.join(' · ')}`, { channel: ch.slug, username: req.user.username });
return res.status(409).json({ error: `No arrancó con la configuración nueva: ${r.errors.join(' · ')}` });
}
} finally { busy.delete(old.id); }
event('info', `Canal editado y reiniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
} else {
event('info', `Canal editado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
}
res.json(getChannel(old.id)); res.json(getChannel(old.id));
}); });
@@ -82,20 +125,54 @@ router.delete('/:id', async (req, res) => {
return res.status(409).json({ error: 'El canal está andando: detenlo antes de borrarlo' }); return res.status(409).json({ error: 'El canal está andando: detenlo antes de borrarlo' });
} }
db.prepare('DELETE FROM channels WHERE id = ?').run(ch.id); db.prepare('DELETE FROM channels WHERE id = ?').run(ch.id);
apply.removeEnv(ch.slug);
event('warn', `Canal borrado: ${ch.name}`, { channel: ch.slug, username: req.user.username }); event('warn', `Canal borrado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
res.json({ ok: true }); res.json({ ok: true });
}); });
for (const act of ['start', 'stop']) { router.post('/:id/start', async (req, res) => {
router.post(`/:id/${act}`, (req, res) => { const ch = getChannel(req.params.id);
if (!CONTROL) return res.status(409).json({ error: CONTROL_OFF_MSG }); if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
res.status(501).json({ error: 'Sin implementar' }); if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
}); const others = await runningOthers(ch);
} if (others.length >= MAX_RUNNING) {
return res.status(409).json({ error: `Ya hay ${others.length} canales andando (${others.join(', ')}): el máximo es ${MAX_RUNNING} por gpu02` });
}
if (throttled(ch.id)) return res.status(429).json({ error: 'Demasiados reinicios de este canal: espera unos minutos' });
busy.add(ch.id);
try {
const r = await apply.start(ch);
if (!r.ok) {
event('error', `No arrancó ${ch.name}: ${r.errors.join(' · ')}`, { channel: ch.slug, username: req.user.username });
return res.status(409).json({ error: `No arrancó: ${r.errors.join(' · ')}` });
}
event('info', `Canal iniciado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
res.json({ ok: true });
} finally { busy.delete(ch.id); }
});
router.post('/:id/stop', async (req, res) => {
const ch = getChannel(req.params.id);
if (!ch) return res.status(404).json({ error: 'Canal inexistente' });
if (busy.has(ch.id)) return res.status(409).json({ error: 'El canal está ocupado con otra operación' });
busy.add(ch.id);
try { await apply.stop(ch); } finally { busy.delete(ch.id); }
event('info', `Canal parado: ${ch.name}`, { channel: ch.slug, username: req.user.username });
res.json({ ok: true });
});
// Base nueva: T13 (el canal de la 076-078, configurado a mano) entra como un canal // Base nueva: T13 (el canal de la 076-078, configurado a mano) entra como un canal
// más, con lo que dice su /etc/orbisubs/t13.env. Solo se lee. // más, con lo que dice su /etc/orbisubs/t13.env. Solo se lee.
function seedT13() { function seedT13() {
// Base creada en la fase 1 (antes de cerrar la 078): T13 sin la marca del HLS de prueba.
const t13 = db.prepare("SELECT * FROM channels WHERE slug = 't13'").get();
if (t13) {
const cfg = JSON.parse(t13.cfg);
if (cfg.srt && cfg.srt.enabled && cfg.srt.test === undefined) {
cfg.srt.test = true;
db.prepare('UPDATE channels SET cfg = ? WHERE id = ?').run(JSON.stringify(cfg), t13.id);
}
}
if (db.prepare('SELECT 1 FROM channels LIMIT 1').get()) return; if (db.prepare('SELECT 1 FROM channels LIMIT 1').get()) return;
const file = (process.env.ORBISUBS_ETC || '/etc/orbisubs') + '/t13.env'; const file = (process.env.ORBISUBS_ETC || '/etc/orbisubs') + '/t13.env';
let env; let env;
@@ -115,7 +192,7 @@ function seedT13() {
hls: { enabled: true, seg_s: 6, list_size: 10 }, hls: { enabled: true, seg_s: 6, list_size: 10 },
srt: env.SRT_PORT ? { srt: env.SRT_PORT ? {
enabled: true, mode: 'listener', port: Number(env.SRT_PORT), latency_ms: 200, delay_s: Number(env.SRT_DELAY || 24), enabled: true, mode: 'listener', port: Number(env.SRT_PORT), latency_ms: 200, delay_s: Number(env.SRT_DELAY || 24),
cc608: { es: 'CC1', en: 'CC3' }, cc708: { es: 1, en: 2 }, cc608: { es: 'CC1', en: 'CC3' }, cc708: { es: 1, en: 2 }, test: true,
} : { enabled: false }, } : { enabled: false },
}, },
}; };
+16
View File
@@ -0,0 +1,16 @@
'use strict';
// reset-admin.js — vuelve la cuenta admin a admin/admin con cambio obligatorio y
// cierra todas sus sesiones. Para una clave olvidada, o para entregar el panel
// limpio después de probarlo. Uso (en el CT, como root):
// DATA_DIR=/var/lib/orbisubs-panel /opt/node/bin/node /opt/orbisubs-panel/tools/reset-admin.js
const crypto = require('crypto');
const { db } = require('../src/db');
const salt = crypto.randomBytes(16).toString('hex');
const iter = 200000;
const hash = crypto.pbkdf2Sync('admin', Buffer.from(salt, 'hex'), iter, 32, 'sha256').toString('hex');
const r = db.prepare(`INSERT INTO users (username, salt, iter, hash, role, must_change) VALUES ('admin', ?, ?, ?, 'admin', 1)
ON CONFLICT(username) DO UPDATE SET salt = excluded.salt, iter = excluded.iter, hash = excluded.hash, must_change = 1, sver = sver + 1`)
.run(salt, iter, hash);
db.prepare("DELETE FROM sessions WHERE username = 'admin'").run();
console.log(r.changes ? 'admin vuelve a admin/admin (pide clave nueva al entrar)' : 'sin cambios');
+2
View File
@@ -13,6 +13,8 @@
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.5.20/dist/hls.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/hls.js@1.5.20/dist/hls.min.js"></script>
<script> <script>
let hls; let hls;
// ?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;
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();