diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 615db1727..3a4decd55 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -285,6 +285,8 @@ jobs:
node --check portal/static/js/booth-reconnect.js
node --check portal/static/js/mic-activity.js
node --check portal/static/js/whep-listener.js
+ node --check portal/static/js/embed-player.js
+ node --check portal/static/js/audio-scheduler.js
node --check portal/static/js/admin.js
node --check portal/static/js/attendance.js
node --check portal/static/js/booth-detail.js
@@ -308,6 +310,7 @@ jobs:
run: |
node tests/test_audio_scheduler.js
node tests/test_tts_parser.js
+ node tests/test_embed_player.js
node --test tests/test_demo_modal.js
node tests/test_listener_event.js
node tests/test_whep_listener.js
diff --git a/portal/auth.py b/portal/auth.py
index f06e16914..53fb4c478 100644
--- a/portal/auth.py
+++ b/portal/auth.py
@@ -162,17 +162,19 @@ def create_listener_token(*, event_slug: str) -> str:
return jwt.encode(payload, settings.effective_jwt_secret, algorithm="HS256")
-def create_embed_token(*, event_slug: str) -> str:
+def create_embed_token(*, event_slug: str, room_id: int | None = None) -> str:
"""Create a short-lived JWT for embed iframe access.
Identical claim shape to create_listener_token (kind='listener', event_slug)
so it passes both the embed route's claim checks and the /ws/captions
WebSocket auth's booth_id.startswith(event_slug + '-') check.
+ When ``room_id`` is provided, /embed, /ws/captions, and /ws/tts enforce
+ that the target channel belongs to that room.
Uses a shorter expiry (embed_token_expiry_seconds, default 30 min) because
the token is visible in the iframe src= attribute in the third party's HTML.
"""
now = datetime.now(timezone.utc)
- payload = {
+ payload: dict[str, object] = {
"sub": str(uuid.uuid4()),
"kind": LISTENER_TOKEN_KIND,
"purpose": "embed",
@@ -180,6 +182,8 @@ def create_embed_token(*, event_slug: str) -> str:
"iat": now,
"exp": now + timedelta(seconds=settings.embed_token_expiry_seconds),
}
+ if room_id is not None:
+ payload["room_id"] = room_id
return jwt.encode(payload, settings.effective_jwt_secret, algorithm="HS256")
@@ -193,6 +197,12 @@ class WSAuthError(Exception):
pass
+class EmbedTokenExpiredError(WSAuthError):
+ """Raised when a short-lived embed WebSocket token has expired."""
+
+ pass
+
+
def token_issued_at(payload: dict) -> datetime | None:
issued_at = payload.get("iat")
if isinstance(issued_at, bool) or not isinstance(issued_at, (int, float)):
diff --git a/portal/routers/listener.py b/portal/routers/listener.py
index d0991bcbd..6ff32e001 100644
--- a/portal/routers/listener.py
+++ b/portal/routers/listener.py
@@ -3,12 +3,14 @@
import asyncio
import json
import re
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, TypedDict
import jwt
from fastapi import APIRouter, HTTPException, Query, Request, status
from fastapi.templating import Jinja2Templates
+from sqlalchemy.ext.asyncio import AsyncSession
from starlette.responses import JSONResponse, Response
from portal.auth import (
@@ -30,6 +32,7 @@
)
from portal.globals import _JS_CACHE_BUST, asset_version_context
from portal.join_code_limit import JoinCodeThrottled, verify_join_code
+from portal.models import Event, Room
from portal.overlay_channels import overlay_channels
from portal.utils import _ensure_mediamtx_path
@@ -37,7 +40,7 @@
_ALLOWED_THEMES = {"dark", "light"}
_ALLOWED_FONTS = {"inter", "roboto", "outfit"}
_PRIMARY_COLOR_RE = re.compile(r"^[0-9a-fA-F]{3,6}$")
-_DEFAULT_PRIMARY = "3b82f6" # VoxBento blue
+_DEFAULT_PRIMARY = "2563eb" # VoxBento primary blue (--vb-color-primary)
_BASE_DIR = Path(__file__).resolve().parent.parent
templates = Jinja2Templates(directory=str(_BASE_DIR / "templates"), context_processors=[asset_version_context])
@@ -250,7 +253,7 @@ async def subtitle_overlay(
return response
-def _verify_embed_token(token: str, event_slug: str) -> None:
+def _verify_embed_token(token: str, event_slug: str) -> dict[str, Any]:
"""Validate the embed token and its listener/embed claims for ``event_slug``.
Raises ``HTTPException(403)`` for a missing, expired, invalid, or mismatched token.
@@ -272,10 +275,20 @@ def _verify_embed_token(token: str, event_slug: str) -> None:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Token must be an embed token.")
if payload.get("event_slug") != event_slug:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Token is not valid for this event.")
+ return payload
-async def _resolve_embed_room(session: Any, ev: Any, room_id: int | None) -> tuple[int, int]:
- """Resolve the target room id and its audio delay for an embed request."""
+@dataclass(frozen=True)
+class EmbedChannel:
+ booth_id: str
+ channel_id: str
+ audio_mode: str = "whep"
+ tts_booth_id: str = ""
+ tts_language_code: str = ""
+
+
+async def _resolve_embed_room(session: AsyncSession, ev: Event, room_id: int | None) -> tuple[Room, int]:
+ """Resolve the target room and its audio delay for an embed request."""
rooms = await list_rooms_for_event(session, ev.id, limit=None)
if room_id is None:
if not rooms:
@@ -285,46 +298,63 @@ async def _resolve_embed_room(session: Any, ev: Any, room_id: int | None) -> tup
status_code=status.HTTP_400_BAD_REQUEST,
detail="This event has multiple rooms. Please use the /embed/{event_slug}/{room_id}/{language_code} URL instead.",
)
- return rooms[0].id, rooms[0].audio_delay_ms
+ return rooms[0], rooms[0].audio_delay_ms
room = next((r for r in rooms if r.id == room_id), None)
if not room:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Room not found.")
- return room.id, room.audio_delay_ms
+ return room, room.audio_delay_ms
async def _resolve_embed_channel(
- session: Any, ev: Any, event_slug: str, room_id: int, language_code: str
-) -> tuple[str, str]:
- """Resolve the booth id and mediamtx channel id for the requested language."""
+ session: AsyncSession, ev: Event, event_slug: str, room: Room, language_code: str
+) -> EmbedChannel:
+ """Resolve the booth id, mediamtx channel id, and audio mode for the requested language."""
from portal.booth_identity import make_booth_id, make_mediamtx_path
+ norm_lang = language_code.lower()
try:
- booth_id = make_booth_id(ev.slug, room_id, language_code.lower())
- channel_id = make_mediamtx_path(ev.slug, room_id, language_code.lower())
+ booth_id = make_booth_id(ev.slug, room.id, norm_lang)
+ channel_id = make_mediamtx_path(ev.slug, room.id, norm_lang)
except ValueError:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Invalid language code.")
- if language_code.lower() != "floor":
- db_booths = await list_booths_for_event(session, ev.id, limit=None)
- booth = next(
- (b for b in db_booths if b.language_code.lower() == language_code.lower() and b.room_id == room_id),
+ if norm_lang == "floor":
+ return EmbedChannel(booth_id=booth_id, channel_id=channel_id, audio_mode="whep")
+
+ db_booths = await list_booths_for_room(session, room.id)
+ booth = next((b for b in db_booths if b.language_code.lower() == norm_lang), None)
+ if booth is not None:
+ return EmbedChannel(booth_id=booth_id, channel_id=channel_id, audio_mode="whep")
+
+ if room.floor_translation_enabled:
+ lang = next(
+ (item for item in room.translation_languages if item.enabled and item.language_code.lower() == norm_lang),
None,
)
- if booth is None:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"No booth for language '{language_code}' in event '{event_slug}'.",
- )
-
- return booth_id, channel_id
+ if lang is not None:
+ if room.floor_tts_enabled and lang.tts_enabled:
+ floor_booth_id = make_booth_id(ev.slug, room.id, "floor")
+ return EmbedChannel(
+ booth_id=booth_id,
+ channel_id="",
+ audio_mode="tts",
+ tts_booth_id=floor_booth_id,
+ tts_language_code=norm_lang,
+ )
+ return EmbedChannel(booth_id=booth_id, channel_id="", audio_mode="none")
+
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail=f"No booth for language '{language_code}' in event '{event_slug}'.",
+ )
def _sanitize_embed_theme(
theme: str, font: str, primary_color: str, custom_css_url: str | None
) -> tuple[str, str, str, str | None]:
"""Sanitize embed theming params: theme, font, and color are allowlisted; custom CSS is accepted from arbitrary HTTPS URLs."""
- safe_theme = theme if theme in _ALLOWED_THEMES else "dark"
+ safe_theme = theme if theme in _ALLOWED_THEMES else "light"
safe_font = font if font in _ALLOWED_FONTS else "inter"
safe_primary = primary_color if _PRIMARY_COLOR_RE.match(primary_color) else _DEFAULT_PRIMARY
@@ -369,6 +399,8 @@ def _build_embed_context(
postmessage_target_origin: str,
allowed_origins_list: list[str],
audio_delay_ms: int,
+ audio_mode: str = "whep",
+ tts_url: str = "",
) -> dict[str, Any]:
"""Assemble the Jinja2 context for the embed template."""
return {
@@ -376,6 +408,8 @@ def _build_embed_context(
"language_code": language_code,
"whep_url": whep_url,
"caption_url": caption_url,
+ "tts_url": tts_url,
+ "audio_mode": audio_mode,
"token": token,
"theme": safe_theme,
"primary_color": safe_primary,
@@ -406,7 +440,7 @@ async def _embed_listener_impl(
target_lang: str | None,
):
# Authentication
- _verify_embed_token(token, event_slug)
+ token_payload = _verify_embed_token(token, event_slug)
# Resolve booth
async with get_session() as session:
@@ -414,12 +448,21 @@ async def _embed_listener_impl(
if not ev:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Event not found.")
- resolved_room_id, audio_delay_ms = await _resolve_embed_room(session, ev, room_id)
- booth_id, channel_id = await _resolve_embed_channel(session, ev, event_slug, resolved_room_id, language_code)
+ room, audio_delay_ms = await _resolve_embed_room(session, ev, room_id)
+ token_room = token_payload.get("room_id")
+ if token_room is not None and str(token_room) != str(room.id):
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Token is not valid for this room.")
+ channel = await _resolve_embed_channel(session, ev, event_slug, room, language_code)
- whep_url = f"{settings.mediamtx_whip_base}/{channel_id}/whep"
+ whep_url = f"{settings.mediamtx_whip_base}/{channel.channel_id}/whep" if channel.audio_mode == "whep" else ""
host = settings.public_base_url.replace("https://", "").replace("http://", "")
- caption_url = f"wss://{host}/ws/captions/{booth_id}"
+ caption_url = f"wss://{host}/ws/captions/{channel.booth_id}"
+ tts_url = (
+ f"wss://{host}/ws/tts/{room.id}/{channel.tts_language_code}/{channel.tts_booth_id}"
+ if channel.audio_mode == "tts"
+ else ""
+ )
+ captions_effective = captions or channel.audio_mode == "none"
# Sanitize theming params
safe_theme, safe_font, safe_primary, safe_custom_css = _sanitize_embed_theme(
@@ -443,13 +486,15 @@ async def _embed_listener_impl(
safe_theme=safe_theme,
safe_primary=safe_primary,
safe_font=safe_font,
- captions=captions,
+ captions=captions_effective,
safe_custom_css=safe_custom_css,
target_lang=target_lang,
headless=headless,
postmessage_target_origin=postmessage_target_origin,
allowed_origins_list=allowed_origins_list,
audio_delay_ms=audio_delay_ms,
+ audio_mode=channel.audio_mode,
+ tts_url=tts_url,
)
return templates.TemplateResponse(request=request, name="embed.html", context=context, headers=response_headers)
@@ -461,7 +506,7 @@ async def embed_listener_legacy(
event_slug: str,
language_code: str,
token: str = Query(""),
- theme: str = Query("dark"),
+ theme: str = Query("light"),
primary_color: str = Query(_DEFAULT_PRIMARY, alias="primaryColor"),
font: str = Query("inter"),
captions: bool = Query(False),
@@ -493,7 +538,7 @@ async def embed_listener_scoped(
room_id: int,
language_code: str,
token: str = Query(""),
- theme: str = Query("dark"),
+ theme: str = Query("light"),
primary_color: str = Query(_DEFAULT_PRIMARY, alias="primaryColor"),
font: str = Query("inter"),
captions: bool = Query(False),
diff --git a/portal/static/css/embed.css b/portal/static/css/embed.css
index cc38706c8..e7b225766 100644
--- a/portal/static/css/embed.css
+++ b/portal/static/css/embed.css
@@ -24,8 +24,9 @@ body {
width: 100%;
max-width: 480px;
background: var(--surface);
- border: 1.5px solid var(--border);
- border-radius: 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--vb-radius-md);
+ box-shadow: var(--vb-shadow-sm);
padding: 20px 24px;
display: flex;
flex-direction: column;
@@ -60,8 +61,9 @@ body {
flex-shrink: 0;
transition: background 0.3s;
}
-.status-dot.live { background: #22c55e; box-shadow: 0 0 6px #22c55e88; }
-.status-dot.error { background: #ef4444; }
+.status-dot.live,
+.status-dot.captions { background: var(--vb-color-live); box-shadow: 0 0 6px color-mix(in srgb, var(--vb-color-live) 53%, transparent); }
+.status-dot.error { background: var(--vb-color-danger); }
.status-dot.connecting { background: var(--primary); animation: pulse 1.2s infinite; }
@keyframes pulse {
@@ -70,6 +72,9 @@ body {
}
/* ── Play button ─────────────────────────────────────────────────────── */
+.play-btn[hidden] {
+ display: none;
+}
.play-btn {
display: flex;
align-items: center;
@@ -78,15 +83,15 @@ body {
width: 100%;
padding: 12px 20px;
border: none;
- border-radius: 8px;
+ border-radius: var(--vb-radius-sm);
background: var(--primary);
color: #fff;
font-family: var(--font);
font-size: 14px;
- font-weight: 700;
+ font-weight: 600;
cursor: pointer;
transition: opacity 0.15s, transform 0.1s;
- letter-spacing: 0.02em;
+ letter-spacing: 0.01em;
}
.play-btn:hover:not(:disabled) { opacity: 0.88; transform: translateY(-1px); }
.play-btn:active:not(:disabled) { transform: translateY(0); }
@@ -98,9 +103,9 @@ body {
max-height: 160px;
overflow-y: auto;
padding: 10px 14px;
- background: var(--bg);
+ background: var(--surface-2, var(--bg));
border: 1px solid var(--border);
- border-radius: 8px;
+ border-radius: var(--vb-radius-sm);
font-size: 13px;
line-height: 1.55;
color: var(--text);
diff --git a/portal/static/js/audio-scheduler.js b/portal/static/js/audio-scheduler.js
index 3dd199342..f0beb54e0 100644
--- a/portal/static/js/audio-scheduler.js
+++ b/portal/static/js/audio-scheduler.js
@@ -43,6 +43,7 @@ function createAudioScheduler(audioCtx, opts) {
? opts.comfortNoiseLevelDb : -40;
var COMFORT_NOISE_FADE_SEC = typeof opts.comfortNoiseFadeSec === 'number'
? opts.comfortNoiseFadeSec : 0.5;
+ var destination = opts.destination || audioCtx.destination;
/** @type {number} audioCtx.currentTime when the last scheduled buffer ends */
var nextScheduledTime = 0;
@@ -95,7 +96,7 @@ function createAudioScheduler(audioCtx, opts) {
comfortNoiseGain.gain.linearRampToValueAtTime(
1, audioCtx.currentTime + COMFORT_NOISE_FADE_SEC
);
- comfortNoiseGain.connect(audioCtx.destination);
+ comfortNoiseGain.connect(destination);
comfortNoiseSource = audioCtx.createBufferSource();
comfortNoiseSource.buffer = getComfortNoiseBuffer();
@@ -196,7 +197,7 @@ function createAudioScheduler(audioCtx, opts) {
var source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
- source.connect(audioCtx.destination);
+ source.connect(destination);
source.onended = function () {
scheduledSources.delete(source);
};
diff --git a/portal/static/js/embed-player.js b/portal/static/js/embed-player.js
index 5a2aef49d..cabfc6609 100644
--- a/portal/static/js/embed-player.js
+++ b/portal/static/js/embed-player.js
@@ -1,63 +1,117 @@
-'use strict';
-
-(function() {
- document.addEventListener('DOMContentLoaded', function() {
- const configEl = document.getElementById('embed-config');
- if (!configEl) {
- console.error('Embed configuration not found.');
- return;
- }
-
- let config;
- try {
- config = JSON.parse(configEl.textContent);
- } catch (e) {
- console.error('Failed to parse embed configuration:', e);
- return;
- }
+export function isJwtExpired(token, nowSeconds = Date.now() / 1000) {
+ if (!token || typeof token !== 'string') return false;
+ const parts = token.split('.');
+ if (parts.length !== 3) return false;
+ try {
+ const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
+ const json = typeof atob === 'function'
+ ? atob(padded)
+ : Buffer.from(padded, 'base64').toString('utf8');
+ const payload = JSON.parse(json);
+ return typeof payload.exp === 'number' && payload.exp <= nowSeconds;
+ } catch (err) {
+ console.error('Failed to decode embed token expiry:', err);
+ return false;
+ }
+}
- const WHEP_URL = config.whep_url;
- const CAPTION_URL = config.caption_url;
- const CAPTIONS_ON = config.captions_enabled;
- const EMBED_TOKEN = config.token;
- const TARGET_LANG = config.target_lang_code;
- const SOURCE_LANG = config.source_lang_code;
+export function initEmbedPlayer(env = {}) {
+ const doc = env.document || document;
+ const win = env.window || window;
+ const WebSocketCtor = env.WebSocket || win.WebSocket;
+ const AudioContextCtor = env.AudioContext || win.AudioContext || win.webkitAudioContext;
+ const whepFactory = env.createWhepClient || win.createWhepClient;
+ const ttsParser = env.TTSParser || win.TTSParser;
+ const audioSchedulerFactory = env.AudioScheduler || win.AudioScheduler;
+ const schedule = env.setTimeout || win.setTimeout.bind(win);
+ const cancel = env.clearTimeout || win.clearTimeout.bind(win);
- const audioEl = document.getElementById('embed-audio');
- const playBtn = document.getElementById('play-btn');
- const statusDot = document.getElementById('status-dot');
- const statusText = document.getElementById('status-text');
- const captionsEl = document.getElementById('captions-box') || null;
+ const configEl = doc.getElementById('embed-config');
+ if (!configEl) {
+ console.error('Embed configuration not found.');
+ return null;
+ }
- let playing = false;
+ let config;
+ try {
+ config = JSON.parse(configEl.textContent);
+ } catch (err) {
+ console.error('Failed to parse embed configuration:', err);
+ return null;
+ }
- function setStatus(state, text) {
- statusDot.className = 'status-dot ' + (state || '');
- statusText.textContent = text;
- }
+ const AUDIO_MODE = config.audio_mode || 'whep';
+ const WHEP_URL = config.whep_url || '';
+ const TTS_URL = config.tts_url || '';
+ const CAPTION_URL = config.caption_url || '';
+ const CAPTIONS_ON = Boolean(config.captions_enabled);
+ const EMBED_TOKEN = config.token || '';
+ const TARGET_LANG = config.target_lang_code || '';
+ const SOURCE_LANG = config.source_lang_code || '';
+ const AUDIO_DELAY_MS = Math.min(Math.max(Number(config.audio_delay_ms) || 0, 0), 10000);
+
+ const audioEl = doc.getElementById('embed-audio');
+ const playBtn = doc.getElementById('play-btn');
+ const statusDot = doc.getElementById('status-dot');
+ const statusText = doc.getElementById('status-text');
+ const captionsEl = doc.getElementById('captions-box') || null;
- function setExpired() {
- setStatus('error', 'Session expired');
+ let playing = false;
+ let expired = false;
+ let captionWs = null;
+ let ttsWs = null;
+ let captionRetryTimer = null;
+ let ttsRetryTimer = null;
+
+ function postToParent(type, payload) {
+ if (!config.headless || !win.parent) return;
+ win.parent.postMessage(
+ { source: 'voxbento-embed', v: 1, type, payload },
+ config.target_origin,
+ );
+ }
+
+ function setStatus(state, text) {
+ statusDot.className = 'status-dot ' + (state || '');
+ statusText.textContent = text;
+ }
+
+ function setExpired() {
+ if (expired) return;
+ expired = true;
+ playing = false;
+ setStatus('error', 'Session expired');
+ if (playBtn) {
playBtn.textContent = '\u26a0 Session Expired \u2014 Reload Host Page';
playBtn.disabled = true;
}
+ if (audioController && audioController.stop) audioController.stop();
+ if (captionRetryTimer) { cancel(captionRetryTimer); captionRetryTimer = null; }
+ if (ttsRetryTimer) { cancel(ttsRetryTimer); ttsRetryTimer = null; }
+ if (captionWs) { const ws = captionWs; captionWs = null; ws.close(); }
+ if (ttsWs) { const ws = ttsWs; ttsWs = null; ws.close(); }
+ postToParent('error', { code: 'session_expired', message: 'Embed token expired' });
+ }
+
+ function buildWsUrl(httpOrWsUrl) {
+ const wsProto = win.location.protocol === 'https:' ? 'wss:' : 'ws:';
+ const urlPath = new URL(httpOrWsUrl).pathname;
+ return wsProto + '//' + win.location.host + urlPath + '?token=' + encodeURIComponent(EMBED_TOKEN);
+ }
- const whep = createWhepClient();
+ // ── Audio Controllers ──────────────────────────────────────────────────
+ function createWhepController() {
+ const whep = whepFactory();
+ let detached = false;
whep.start({
whepUrl: WHEP_URL,
- audioEl: audioEl,
+ audioEl,
audioDelayMs: config.audio_delay_ms,
- onState: function(s) {
- if (config.headless) {
- window.parent.postMessage({
- source: 'voxbento-embed',
- v: 1,
- type: 'booth_state',
- payload: { state: s.peerConnection }
- }, config.target_origin);
- }
-
+ onState(s) {
+ if (detached) return;
+ postToParent('booth_state', { state: s.peerConnection });
if (s.peerConnection === 'connected') {
setStatus('live', 'Live');
playBtn.disabled = false;
@@ -69,176 +123,513 @@
setStatus('connecting', 'Connecting\u2026');
}
},
- onLog: function() {},
+ onLog() {},
});
- playBtn.addEventListener('click', function() {
- if (!playing) {
- audioEl.play().then(function() {
- playing = true;
- playBtn.textContent = '\u23f8 Pause';
- }).catch(function() {
- setStatus('error', 'Playback blocked \u2014 check browser permissions');
- });
- } else {
+ let whepPlayRequestId = 0;
+
+ return {
+ play() {
+ if (expired) return Promise.reject(new Error('Session expired'));
+ const reqId = ++whepPlayRequestId;
+ return audioEl.play().then(
+ () => {
+ if (reqId !== whepPlayRequestId) return;
+ if (expired) {
+ audioEl.pause();
+ return;
+ }
+ playing = true;
+ playBtn.textContent = '\u23f8 Pause';
+ },
+ (err) => {
+ if (reqId !== whepPlayRequestId || expired) return;
+ throw err;
+ },
+ );
+ },
+ pause() {
+ whepPlayRequestId++;
audioEl.pause();
playing = false;
playBtn.textContent = '\u25b6 Play Audio';
+ },
+ stop() {
+ detached = true;
+ whepPlayRequestId++;
+ if (whep && typeof whep.stop === 'function') whep.stop();
+ audioEl.pause();
+ playing = false;
+ },
+ setVolume(v) {
+ audioEl.volume = v;
+ },
+ };
+ }
+
+ function createTtsController() {
+ let audioCtx = null;
+ let gainNode = null;
+ let audioScheduler = null;
+ let playRequestId = 0;
+ let resumeInFlight = false;
+ let currentVolume = 1;
+ let ttsRetryDelayMs = 1000;
+ let segmentStore = Object.create(null);
+ let expectedSeq = null;
+ let isSegmentPlaying = false;
+ let seqWaitTimer = null;
+ let fallbackQueueTimer = null;
+ const delayTimers = new Set();
+
+ function ensureAudioGraph() {
+ if (!audioCtx) {
+ const ctx = new AudioContextCtor();
+ const gain = ctx.createGain();
+ gain.gain.value = currentVolume;
+ gain.connect(ctx.destination);
+ const sched = audioSchedulerFactory.create(ctx, {
+ jitterBufferSec: 0.25,
+ comfortNoiseEnabled: false,
+ destination: gain,
+ });
+ audioCtx = ctx;
+ gainNode = gain;
+ audioScheduler = sched;
}
- });
+ return audioCtx;
+ }
+
+ function clearPendingPlayback() {
+ delayTimers.forEach((t) => cancel(t));
+ delayTimers.clear();
+ if (seqWaitTimer) { cancel(seqWaitTimer); seqWaitTimer = null; }
+ if (fallbackQueueTimer) { cancel(fallbackQueueTimer); fallbackQueueTimer = null; }
+ segmentStore = Object.create(null);
+ expectedSeq = null;
+ isSegmentPlaying = false;
+ if (audioScheduler) {
+ audioScheduler.reset();
+ }
+ }
- if (CAPTIONS_ON && captionsEl) {
- var wsProto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
- var urlPath = new URL(CAPTION_URL).pathname;
- var wsUrl = wsProto + '//' + window.location.host + urlPath + '?token=' + encodeURIComponent(EMBED_TOKEN);
- var captionWs = null;
- var captionRetryDelayMs = 1000;
-
- var historyEl = document.getElementById('embed-caption-history');
- var currentEl = document.getElementById('embed-caption-current');
- var maxHistoryDOM = 50;
- // How close to the bottom (in px) still counts as "following" the captions.
- var FOLLOW_THRESHOLD_PX = 40;
-
- var captionHistoryHeadless = [];
- var maxHistoryHeadless = 2;
-
- function handleCaptionMessage(ev) {
+ function advanceSeq(seqId) {
+ isSegmentPlaying = false;
+ delete segmentStore[seqId];
+ expectedSeq++;
+ fallbackQueueTimer = schedule(pumpSegmentQueue, 30);
+ }
+
+ function pumpSegmentQueue() {
+ if (!playing || isSegmentPlaying) return;
+ const nextSeg = segmentStore[expectedSeq];
+ if (!nextSeg) {
+ if (!seqWaitTimer) {
+ seqWaitTimer = schedule(() => {
+ seqWaitTimer = null;
+ const storedSeqs = Object.keys(segmentStore).map(Number).filter((n) => !isNaN(n)).sort((a, b) => a - b);
+ const nextAvailable = storedSeqs.find((s) => s > expectedSeq);
+ if (nextAvailable !== undefined) {
+ expectedSeq = nextAvailable;
+ pumpSegmentQueue();
+ }
+ }, 1500);
+ }
+ return;
+ }
+
+ if (seqWaitTimer) { cancel(seqWaitTimer); seqWaitTimer = null; }
+ isSegmentPlaying = true;
+
+ if (nextSeg.error || nextSeg.empty) {
+ advanceSeq(expectedSeq);
+ return;
+ }
+
+ if (nextSeg.audioBuffer && audioScheduler) {
+ const finishedSeq = expectedSeq;
+ audioScheduler.scheduleBuffer(nextSeg.audioBuffer);
+ advanceSeq(finishedSeq);
+ } else {
+ // Waiting for Stage 2 audio: arm seqWaitTimer so a dropped Stage-2 frame cannot stall forever.
+ isSegmentPlaying = false;
+ if (!seqWaitTimer) {
+ const elapsed = Date.now() - (nextSeg.receivedAt || Date.now());
+ seqWaitTimer = schedule(() => {
+ seqWaitTimer = null;
+ if (segmentStore[expectedSeq]) {
+ segmentStore[expectedSeq].error = 'tts_timeout';
+ }
+ pumpSegmentQueue();
+ }, Math.max(0, 65000 - elapsed));
+ }
+ }
+ }
+
+ function processFrame(frame) {
+ if (!playing) return;
+ const seq = frame.header && frame.header.seq;
+ if (!seq) return;
+ if (expectedSeq === null || expectedSeq === undefined) expectedSeq = seq;
+ if (seq < expectedSeq) return;
+
+ const hasAudio = Boolean(!frame.header.error && frame.audioBytes && frame.audioBytes.byteLength > 0);
+ let audioBuffer = null;
+ if (hasAudio && audioCtx) {
+ const aligned = frame.audioBytes.buffer.slice(
+ frame.audioBytes.byteOffset,
+ frame.audioBytes.byteOffset + frame.audioBytes.byteLength,
+ );
+ const int16 = new Int16Array(aligned);
+ const float32 = new Float32Array(int16.length);
+ for (let i = 0; i < int16.length; i++) {
+ float32[i] = int16[i] / 32768.0;
+ }
+ audioBuffer = audioCtx.createBuffer(1, float32.length, 24000);
+ audioBuffer.copyToChannel(float32, 0);
+ }
+
+ segmentStore[seq] = {
+ seq,
+ error: frame.header.error || (frame.header.audio_pending === false && !hasAudio ? 'no_audio' : null),
+ empty: !frame.header.translation && !frame.header.error && frame.header.audio_pending === false,
+ audioBuffer,
+ receivedAt: (segmentStore[seq] && segmentStore[seq].receivedAt) || Date.now(),
+ };
+
+ const storedSeqs = Object.keys(segmentStore).map(Number).sort((a, b) => a - b);
+ if (storedSeqs.length > 5) {
+ while (storedSeqs.length > 5) {
+ const oldest = storedSeqs.shift();
+ delete segmentStore[oldest];
+ }
+ expectedSeq = storedSeqs[0];
+ if (seqWaitTimer) {
+ cancel(seqWaitTimer);
+ seqWaitTimer = null;
+ }
+ }
+ pumpSegmentQueue();
+ }
+
+ function openTtsWs() {
+ if (expired || !TTS_URL) return;
+ const ws = new WebSocketCtor(buildWsUrl(TTS_URL));
+ ws.binaryType = 'arraybuffer';
+ ttsWs = ws;
+ setStatus('connecting', 'Connecting\u2026');
+ postToParent('booth_state', { state: 'connecting' });
+
+ ws.onopen = function () {
+ if (ttsWs !== ws) return;
+ setStatus('live', 'Live');
+ playBtn.disabled = false;
+ playBtn.textContent = playing ? '\u23f8 Pause' : '\u25b6 Play Audio';
+ postToParent('booth_state', { state: 'connected' });
+ };
+
+ ws.onmessage = function (ev) {
+ if (ttsWs !== ws) return;
+ ttsRetryDelayMs = 1000;
+ if (!(ev.data instanceof ArrayBuffer) || !playing) return;
try {
- var msg = JSON.parse(ev.data);
- var isValid = false;
- if (config.headless) {
- // Headless: Forward both the original captions and the requested translations
- if (msg.type === 'caption') isValid = true;
- if (msg.type === 'translation' && msg.language_code === TARGET_LANG) isValid = true;
+ const frame = ttsParser.parseFrame(ev.data);
+ if (AUDIO_DELAY_MS > 0) {
+ const timer = schedule(() => {
+ delayTimers.delete(timer);
+ processFrame(frame);
+ }, AUDIO_DELAY_MS);
+ delayTimers.add(timer);
} else {
- // Visible UI: Only show one language track to prevent overlapping text
- const isTranslating = TARGET_LANG && TARGET_LANG !== SOURCE_LANG;
- if (isTranslating) {
- if (msg.type === 'translation' && msg.language_code === TARGET_LANG) isValid = true;
- } else {
- if (msg.type === 'caption') isValid = true;
- }
+ processFrame(frame);
}
-
- if (isValid) {
- var status = msg.type === 'translation' ? 'final' : (msg.status || 'final');
- var text = (msg.text || '').trim();
-
- if (config.headless) {
- // Headless: maintain a short array buffer and send concatenated string
- if (status === 'clear') {
- captionHistoryHeadless = [];
- text = '';
- } else if (status === 'final') {
- if (text) {
- captionHistoryHeadless.push(text);
- if (captionHistoryHeadless.length > maxHistoryHeadless) {
- captionHistoryHeadless.shift();
- }
- }
- text = '';
- }
- var displayText = captionHistoryHeadless.concat(text ? [text] : []).join(' ');
-
- window.parent.postMessage({
- source: 'voxbento-embed',
- v: 1,
- type: 'subtitle',
- payload: {
- text: displayText,
- language: msg.language_code || SOURCE_LANG,
- msg_type: msg.type,
- raw_status: status,
- raw_text: msg.text
- }
- }, config.target_origin);
- } else {
- // Visible UI: build a DOM history like Voxbento's main listener UI.
- // Follow new captions only while the viewer is already at the bottom,
- // so scrolling up to re-read a line is not undone by the next partial.
- var followLatest =
- captionsEl.scrollHeight - captionsEl.scrollTop - captionsEl.clientHeight <= FOLLOW_THRESHOLD_PX;
- if (status === 'clear') {
- currentEl.textContent = '';
- } else if (status === 'final') {
- if (text) {
- var p = document.createElement('div');
- p.textContent = text;
- historyEl.appendChild(p);
- while (historyEl.children.length > maxHistoryDOM) {
- historyEl.removeChild(historyEl.firstChild);
- }
- }
- currentEl.textContent = '';
- } else if (status === 'partial') {
- currentEl.textContent = text;
- }
-
- if (historyEl.children.length === 0 && !currentEl.textContent) {
- captionsEl.classList.add('empty');
- } else {
- captionsEl.classList.remove('empty');
- }
- if (followLatest) {
- captionsEl.scrollTop = captionsEl.scrollHeight;
- }
+ } catch (err) {
+ console.error('TTS frame parse error:', err);
+ }
+ };
+ ws.onclose = function (ev) {
+ if (ttsWs !== ws) return;
+ ttsWs = null;
+ clearPendingPlayback();
+ if (ev.code === 4001 || ev.code === 4003 || (ev.code === 1006 && isJwtExpired(EMBED_TOKEN))) {
+ setExpired();
+ return;
+ }
+ setStatus('connecting', 'Reconnecting\u2026');
+ postToParent('booth_state', { state: 'connecting' });
+ ttsRetryTimer = schedule(openTtsWs, ttsRetryDelayMs * (0.5 + Math.random() / 2));
+ ttsRetryDelayMs = Math.min(ttsRetryDelayMs * 2, 15000);
+ };
+ }
+
+ openTtsWs();
+
+ return {
+ play() {
+ if (expired) return Promise.reject(new Error('Session expired'));
+ const reqId = ++playRequestId;
+ return Promise.resolve()
+ .then(() => {
+ if (reqId !== playRequestId || expired) return null;
+ return ensureAudioGraph();
+ })
+ .then((ctx) => {
+ if (!ctx || reqId !== playRequestId || expired) return null;
+ resumeInFlight = true;
+ return ctx.resume().then(
+ () => {
+ resumeInFlight = false;
+ return ctx;
+ },
+ (err) => {
+ resumeInFlight = false;
+ throw err;
+ },
+ );
+ })
+ .then((ctx) => {
+ if (!ctx || reqId !== playRequestId || expired) return;
+ if (ctx.state !== 'running') {
+ throw new Error('AudioContext resume blocked');
}
+ playing = true;
+ playBtn.textContent = '\u23f8 Pause';
+ });
+ },
+ pause() {
+ const reqId = ++playRequestId;
+ playing = false;
+ clearPendingPlayback();
+ if (audioCtx && (audioCtx.state === 'running' || resumeInFlight)) {
+ Promise.resolve(audioCtx.suspend()).catch((err) => {
+ if (reqId === playRequestId) console.error('AudioContext suspend failed:', err);
+ });
+ }
+ playBtn.textContent = '\u25b6 Play Audio';
+ },
+ stop() {
+ const reqId = ++playRequestId;
+ playing = false;
+ clearPendingPlayback();
+ if (audioCtx) {
+ const ctx = audioCtx;
+ audioCtx = null;
+ gainNode = null;
+ audioScheduler = null;
+ if (typeof ctx.close === 'function' && ctx.state !== 'closed') {
+ Promise.resolve(ctx.close()).catch((err) => {
+ if (reqId === playRequestId) console.error('AudioContext close failed:', err);
+ });
+ } else if (ctx.state === 'running' || resumeInFlight) {
+ Promise.resolve(ctx.suspend()).catch((err) => {
+ if (reqId === playRequestId) console.error('AudioContext suspend failed:', err);
+ });
}
- } catch (_) {}
- }
-
- function openCaptionWs() {
- var ws = new WebSocket(wsUrl);
- captionWs = ws;
- ws.onopen = function() {
- captionRetryDelayMs = 1000;
- };
- ws.onmessage = handleCaptionMessage;
- ws.onclose = function(ev) {
- if (ev.code === 4001) { setExpired(); return; }
- // 4003: the token is for another event, so reconnecting cannot help.
- if (ev.code === 4003 || captionWs !== ws) return;
- // Any other close (network drop, server restart, proxy timeout) would
- // otherwise stop captions until the host page is reloaded.
- captionWs = null;
- // Wait between half and all of the current delay, so embeds dropped by the same
- // restart do not all reconnect at the same moment.
- setTimeout(openCaptionWs, captionRetryDelayMs * (0.5 + Math.random() / 2));
- captionRetryDelayMs = Math.min(captionRetryDelayMs * 2, 15000);
- };
+ }
+ },
+ setVolume(v) {
+ currentVolume = v;
+ if (gainNode) gainNode.gain.value = v;
+ },
+ };
+ }
+
+ function createNoneController() {
+ if (playBtn) playBtn.hidden = true;
+ if (CAPTIONS_ON && (captionsEl || config.headless) && CAPTION_URL) {
+ setStatus('connecting', 'Connecting captions\u2026');
+ } else {
+ setStatus('error', 'Captions unavailable');
+ }
+ return {
+ play() { return Promise.resolve(); },
+ pause() {},
+ setVolume() {},
+ };
+ }
+
+ const audioController =
+ AUDIO_MODE === 'tts'
+ ? createTtsController()
+ : AUDIO_MODE === 'none'
+ ? createNoneController()
+ : createWhepController();
+
+ if (playBtn && AUDIO_MODE !== 'none') {
+ playBtn.addEventListener('click', function () {
+ if (!playing) {
+ audioController.play().catch((err) => {
+ console.error('Playback blocked:', err);
+ setStatus('error', 'Playback blocked \u2014 check browser permissions');
+ });
+ } else {
+ audioController.pause();
}
+ });
+ }
+
+ // ── Captions WebSocket ─────────────────────────────────────────────────
+
+ if (CAPTIONS_ON && (captionsEl || config.headless) && CAPTION_URL) {
+ const wsUrl = buildWsUrl(CAPTION_URL);
+ let captionRetryDelayMs = 1000;
+ const historyEl = doc.getElementById('embed-caption-history');
+ const currentEl = doc.getElementById('embed-caption-current');
+ const maxHistoryDOM = 50;
+ const FOLLOW_THRESHOLD_PX = 40;
+ let captionHistoryHeadless = [];
+ const maxHistoryHeadless = 2;
- openCaptionWs();
+ function isCaptionRelevant(msg) {
+ if (config.headless) {
+ if (msg.type === 'caption') return true;
+ if (msg.type === 'translated_caption' && (!msg.language_code || msg.language_code === TARGET_LANG)) return true;
+ if (msg.type === 'translation' && msg.language_code === TARGET_LANG) return true;
+ return false;
+ }
+ const isTranslating = Boolean(TARGET_LANG && TARGET_LANG !== SOURCE_LANG) || AUDIO_MODE !== 'whep';
+ if (isTranslating) {
+ if (msg.type === 'translated_caption' && (!msg.language_code || msg.language_code === TARGET_LANG)) return true;
+ if (msg.type === 'translation' && msg.language_code === TARGET_LANG) return true;
+ return false;
+ }
+ return msg.type === 'caption';
}
- if (config.headless) {
- window.addEventListener('message', function(event) {
- if (config.allowed_origins.length > 0 && !config.allowed_origins.includes(event.origin)) return;
- if (!event.data || event.data.source !== 'voxbento-parent') return;
+ function handleCaptionMessage(ev) {
+ let msg;
+ try {
+ msg = JSON.parse(ev.data);
+ } catch (err) {
+ console.error('Invalid caption JSON:', err);
+ return;
+ }
+ if (!isCaptionRelevant(msg)) return;
+
+ const status = (msg.type === 'translation' || msg.type === 'translated_caption')
+ ? 'final'
+ : (msg.status || 'final');
+ let text = (msg.text || '').trim();
- if (event.data.type === 'play') {
- audioEl.play().then(function() {
- playing = true;
- }).catch(function(err) {
- window.parent.postMessage({
- source: 'voxbento-embed',
- v: 1,
- type: 'error',
- payload: { code: 'autoplay_blocked', message: err.message }
- }, config.target_origin);
- });
+ if (config.headless) {
+ if (status === 'clear') {
+ captionHistoryHeadless = [];
+ text = '';
+ } else if (status === 'final') {
+ if (text) {
+ captionHistoryHeadless.push(text);
+ if (captionHistoryHeadless.length > maxHistoryHeadless) {
+ captionHistoryHeadless.shift();
+ }
+ }
+ text = '';
+ }
+ const displayText = captionHistoryHeadless.concat(text ? [text] : []).join(' ');
+ postToParent('subtitle', {
+ text: displayText,
+ language: msg.language_code || TARGET_LANG || SOURCE_LANG,
+ msg_type: msg.type,
+ raw_status: status,
+ raw_text: msg.text,
+ });
+ return;
+ }
+
+ const followLatest =
+ captionsEl.scrollHeight - captionsEl.scrollTop - captionsEl.clientHeight <= FOLLOW_THRESHOLD_PX;
+ if (status === 'clear') {
+ currentEl.textContent = '';
+ } else if (status === 'final') {
+ if (text) {
+ const p = doc.createElement('div');
+ p.textContent = text;
+ historyEl.appendChild(p);
+ while (historyEl.children.length > maxHistoryDOM) {
+ historyEl.removeChild(historyEl.firstChild);
+ }
+ }
+ currentEl.textContent = '';
+ } else if (status === 'partial') {
+ currentEl.textContent = text;
+ }
+
+ if (historyEl.children.length === 0 && !currentEl.textContent) {
+ captionsEl.classList.add('empty');
+ } else {
+ captionsEl.classList.remove('empty');
+ }
+ if (followLatest) {
+ captionsEl.scrollTop = captionsEl.scrollHeight;
+ }
+ }
+
+ function openCaptionWs() {
+ if (expired) return;
+ const ws = new WebSocketCtor(wsUrl);
+ captionWs = ws;
+ ws.onopen = function () {
+ if (captionWs !== ws) return;
+ if (AUDIO_MODE === 'none') {
+ setStatus('captions', 'Captions only');
+ postToParent('booth_state', { state: 'connected' });
}
- if (event.data.type === 'pause') {
- audioEl.pause();
- playing = false;
+ };
+ ws.onmessage = function (ev) {
+ if (captionWs !== ws) return;
+ captionRetryDelayMs = 1000;
+ handleCaptionMessage(ev);
+ };
+ ws.onclose = function (ev) {
+ if (captionWs !== ws) return;
+ if (ev.code === 4001) { setExpired(); return; }
+ if (ev.code === 4003) {
+ captionWs = null;
+ if (AUDIO_MODE === 'none') setStatus('error', 'Access denied');
+ postToParent('error', { code: 'access_denied', message: 'Captions access denied' });
+ return;
}
- if (event.data.type === 'set_volume') {
- const v = Number(event.data.volume);
- if (v >= 0 && v <= 1) audioEl.volume = v;
+ captionWs = null;
+ if (AUDIO_MODE === 'none') {
+ setStatus('connecting', 'Reconnecting\u2026');
+ postToParent('booth_state', { state: 'connecting' });
}
- });
+ captionRetryTimer = schedule(openCaptionWs, captionRetryDelayMs * (0.5 + Math.random() / 2));
+ captionRetryDelayMs = Math.min(captionRetryDelayMs * 2, 15000);
+ };
}
+
+ openCaptionWs();
+ }
+
+ // ── Headless Parent Commands ───────────────────────────────────────────
+
+ if (config.headless) {
+ win.addEventListener('message', function (event) {
+ if (event.source !== win.parent) return;
+ if (config.allowed_origins.length > 0 && !config.allowed_origins.includes(event.origin)) return;
+ if (!event.data || event.data.source !== 'voxbento-parent') return;
+
+ if (event.data.type === 'play') {
+ audioController.play().catch((err) => {
+ postToParent('error', { code: 'autoplay_blocked', message: err.message });
+ });
+ }
+ if (event.data.type === 'pause') {
+ audioController.pause();
+ }
+ if (event.data.type === 'set_volume') {
+ const v = Number(event.data.volume);
+ if (v >= 0 && v <= 1) audioController.setVolume(v);
+ }
+ });
+ }
+
+ return { audioController };
+}
+
+if (typeof document !== 'undefined') {
+ document.addEventListener('DOMContentLoaded', function () {
+ initEmbedPlayer();
});
-})();
+}
diff --git a/portal/templates/embed.html b/portal/templates/embed.html
index e3d3e54ee..ef4c012c6 100644
--- a/portal/templates/embed.html
+++ b/portal/templates/embed.html
@@ -22,6 +22,7 @@
>
+
{% if custom_css_url %}
@@ -33,19 +34,21 @@
/* ── CSS variables — all values are server-sanitised ─────────────────── */
:root {
--primary: #{{ primary_color }};
- --font: '{{ font_family }}', Inter, system-ui, sans-serif;
+ --font: '{{ font_family }}', var(--vb-font);
{% if theme == "dark" %}
- --bg: #0d0f10;
- --surface: #1a1d21;
- --border: #2a2d32;
- --text: #f1f5f9;
- --muted: #94a3b8;
+ --bg: #0d0f10;
+ --surface: #1a1d21;
+ --surface-2: #14171a;
+ --border: #2a2d32;
+ --text: #f1f5f9;
+ --muted: #94a3b8;
{% else %}
- --bg: #f8f9fa;
- --surface: #ffffff;
- --border: #e2e8f0;
- --text: #0d0f10;
- --muted: #64748b;
+ --bg: var(--vb-color-bg);
+ --surface: var(--vb-color-surface);
+ --surface-2: var(--vb-color-surface-2);
+ --border: var(--vb-color-border);
+ --text: var(--vb-color-text);
+ --muted: var(--vb-color-muted);
{% endif %}
}
@@ -61,7 +64,7 @@
Connecting…
-