From 27336b10c7e094b26bee3fcca57cb36a4d79c9fa Mon Sep 17 00:00:00 2001
From: maithilijoshi20 <97733343+maithilijoshi20@users.noreply.github.com>
Date: Mon, 30 Nov 2026 15:36:21 +0900
Subject: [PATCH 1/3] feat(broadcast): Share one CPU puppet across the pilot
console and viewers
## summary
Keep the upstream connection and rundown in the broadcast process. Give each browser a short lived ticket and resume playback from the current chunk when it joins.
Signed-off-by: maithilijoshi20 <97733343+maithilijoshi20@users.noreply.github.com>
---
docs/README.md | 1 +
tools/broadcast_pilot/README.md | 81 ++++++++
tools/broadcast_pilot/check_browsers.py | 49 +++++
tools/broadcast_pilot/client.js | 114 +++++++++++
tools/broadcast_pilot/index.html | 20 ++
tools/broadcast_pilot/server.py | 262 ++++++++++++++++++++++++
tools/broadcast_pilot/test_pilot.py | 154 ++++++++++++++
7 files changed, 681 insertions(+)
create mode 100644 tools/broadcast_pilot/README.md
create mode 100644 tools/broadcast_pilot/check_browsers.py
create mode 100644 tools/broadcast_pilot/client.js
create mode 100644 tools/broadcast_pilot/index.html
create mode 100644 tools/broadcast_pilot/server.py
create mode 100644 tools/broadcast_pilot/test_pilot.py
diff --git a/docs/README.md b/docs/README.md
index dff1456cc..4c9df2ff7 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -28,6 +28,7 @@ This directory is the entry point for the repository's shared documentation. The
| [Business CLI](guides/cli.md) | Querying, editing, and generating through a terminal or Agent Shell | Commands, authorization, or receipt semantics change |
| [DeepSeek Harness plugin](../plugins/deepseek-harness/README.md) | Installing the DSH bundle and editing an OpenDirector project from DSH | Plugin setup, tools, or creation workflows change |
| [Video model capabilities](guides/video-model-capabilities.md) ([中文](guides/video-model-capabilities.zh-CN.md)) | Declaring output specifications supported by a service | Configuration fields or capability integration changes |
+| [CPU broadcast pilot](../tools/broadcast_pilot/README.md) | Running one puppet host for a producer console and multiple viewers | Pilot launch, access or transport changes |
| [Video gateway](guides/video-gateway.md) ([中文](guides/video-gateway.zh-CN.md)) | Serving several H3 LoRA variants from one vLLM-Omni server through the gateway started with the application | Gateway configuration keys, startup, or rewrite behavior change |
| [Model availability / 模型可用状态](guides/model-availability.md) | Optional runtime declarations, automatic checks, shared admission and API/CLI/Agent queries | Capability protocol, refresh, or acceptance rules change |
| [OpenAI Images](guides/openai-images.md) | Wiring gpt-image as an optional image service, request shape and failures | Integration fields, capability scope, or the OpenAI interface change |
diff --git a/tools/broadcast_pilot/README.md b/tools/broadcast_pilot/README.md
new file mode 100644
index 000000000..84258f5ad
--- /dev/null
+++ b/tools/broadcast_pilot/README.md
@@ -0,0 +1,81 @@
+# CPU broadcast pilot
+
+Run a local show with one CPU puppet, a producer console and a read-only viewer page.
+Start the puppet first. Starting the pilot opens the host session and sends the
+opening cue, even with no browsers connected. A producer can advance the rundown
+or end the show. Reloading a page attaches to the current segment.
+
+## Run a show
+
+Use Python 3.11 or newer. From the OpenDirector root on Linux or WSL:
+
+```sh
+python3 -m venv /tmp/od-broadcast
+. /tmp/od-broadcast/bin/activate
+pip install 'aiohttp>=3.10,<4' 'uvicorn[standard]' fastapi numpy pillow scipy httpx pyyaml
+git clone https://github.com/tzhouam/live-agent.git /tmp/od-live-agent
+git -C /tmp/od-live-agent checkout 5da34726942ea7f7e6b5253dd991e09f96db207e
+(cd /tmp/od-live-agent && python -m live_agent.backend.app \
+ --generator puppet --puppet-tts synth --llm-url scripted --vlm-url mock \
+ --asr-url '' --memory-db '' --host 127.0.0.1 --port 8201)
+```
+
+In a second terminal at the OpenDirector root:
+
+```sh
+. /tmp/od-broadcast/bin/activate
+python tools/broadcast_pilot/server.py \
+ --segment 'Open the book discussion' --segment 'Introduce the first reading' --segment 'Close the show'
+```
+
+Open the producer URL printed in the terminal. Share the viewer URL with another
+browser on the same machine. Use **Enable audio** to hear subsequent puppet audio.
+The offline voice produces synthetic sounds. Choose **Next segment** to cue the
+host or **End show** to close its connection. Restart the pilot for a new show.
+
+The pilot runs separately from the editor and binds to loopback. Each browser
+requests a 30-second, single-use ticket from its own origin and redeems it in
+the first WebSocket message. Only the private producer link grants control.
+The producer key stays in the URL fragment until the console saves it in tab
+session storage for refresh. The viewer link contains no credentials.
+
+## Programme connection
+
+The broadcast sends a public JPEG-mode hello to the puppet's `/ws`. It owns
+the rundown position and paces complete JPEG and mono PCM16 chunks on one clock.
+A joining browser gets the current segment and the offset into the playing
+chunk. A slow subscriber moves on to the current chunk without holding up other
+subscribers. A puppet stop discards partial and queued media. Loss of the
+upstream puts the show offline. Only a new pilot process starts another host.
+
+The upstream chunk start and end messages describe the pilot programme clock.
+Viewer paint timestamps, spoken cue verification, audience questions, recording
+and GPU integration belong to follow-up work.
+
+## Verify
+
+Run the local protocol checks from the OpenDirector root:
+
+```sh
+python -m unittest discover -s tools/broadcast_pilot -p test_pilot.py -v
+```
+
+For the browser check, start a fresh show with at least two segments and set
+`PRODUCER_URL` to the private link printed at startup. The check ends the show.
+
+```sh
+pip install playwright
+playwright install --with-deps chromium
+python tools/broadcast_pilot/check_browsers.py
+```
+
+The check uses independent Chromium clients, verifies that puppet frames advance
+after a console refresh and a viewer departure, and compares the host ID and
+rundown across clients.
+
+## 本地试播
+
+按上面的命令先启动 CPU 木偶服务,再启动导播程序。使用终端输出的私有导播链接
+进入导播台,将观众链接交给同机的其他浏览器。点击「开启声音」可收听后续音频。
+「下一环节」切换所有观众看到的节目单位置;「结束直播」关闭主播连接。刷新导播台
+或关闭一个观众页,其他观众仍可继续观看。每次试播只有一个主播,离线合成音不包含真实语音。
diff --git a/tools/broadcast_pilot/check_browsers.py b/tools/broadcast_pilot/check_browsers.py
new file mode 100644
index 000000000..2733b528e
--- /dev/null
+++ b/tools/broadcast_pilot/check_browsers.py
@@ -0,0 +1,49 @@
+"""Exercise a running pilot with independent Chromium clients (requires Playwright)."""
+import os
+import re
+
+from playwright.sync_api import expect, sync_playwright
+
+
+def advancing(page):
+ canvas = page.locator("canvas")
+ expect(canvas).to_have_attribute("data-frame", re.compile(r".+"), timeout=20000)
+ previous = canvas.get_attribute("data-frame")
+ expect(canvas).not_to_have_attribute("data-frame", previous, timeout=15000)
+
+
+def main():
+ producer_url = os.environ["PRODUCER_URL"]
+ viewer_url = producer_url.split("/producer", 1)[0] + "/viewer"
+ with sync_playwright() as playwright:
+ console = playwright.chromium.launch()
+ audience = playwright.chromium.launch()
+ producer = console.new_page(locale="en-US")
+ first = audience.new_page(locale="en-US")
+ late = audience.new_page(locale="zh-CN")
+ producer.goto(producer_url)
+ first.goto(viewer_url)
+ advancing(first)
+ host = first.locator("#host").text_content()
+ assert host and producer.locator("#host").text_content() == host
+ producer.locator("#next").click()
+ expect(first.locator("#position")).to_contain_text("2 /")
+ late.goto(viewer_url)
+ advancing(late)
+ assert first.locator("#segment").text_content() == late.locator("#segment").text_content()
+ producer.reload()
+ advancing(producer)
+ assert producer.locator("#host").text_content() == host
+ first.close()
+ advancing(late)
+ assert late.locator("#host").text_content() == host
+ assert late.locator("#controls").is_hidden()
+ producer.locator("#end").click()
+ late.get_by_text("直播已结束", exact=True).wait_for()
+ print("Shared segment, host identity, refresh, viewer departure and show end passed:", host)
+ audience.close()
+ console.close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/broadcast_pilot/client.js b/tools/broadcast_pilot/client.js
new file mode 100644
index 000000000..f8785652c
--- /dev/null
+++ b/tools/broadcast_pilot/client.js
@@ -0,0 +1,114 @@
+const el = id => document.getElementById(id);
+const zh = navigator.language.toLowerCase().startsWith("zh");
+document.documentElement.lang = zh ? "zh-CN" : "en-US";
+const t = (en, cn) => zh ? cn : en;
+const producer = location.pathname === "/producer";
+const states = {
+ connecting: t("Connecting", "连接中"), live: t("On air", "直播中"),
+ offline: t("Host offline", "主播已离线"), ended: t("Show ended", "直播已结束"),
+};
+el("title").textContent = producer ? t("Producer console", "导播台") : t("Programme feed", "节目直播");
+el("next").textContent = t("Next segment", "下一环节");
+el("end").textContent = t("End show", "结束直播");
+el("viewer").textContent = t("Open viewer", "打开观众页");
+el("sound").textContent = t("Enable audio", "开启声音");
+el("screen").setAttribute("aria-label", t("Live puppet", "实时木偶"));
+el("controls").hidden = !producer;
+el("status").textContent = states.connecting;
+
+let audio, source, animation, sequence = 0, incoming, socket, position;
+function stopPlayback() {
+ sequence++;
+ cancelAnimationFrame(animation);
+ if (source) { source.stop(); source = null; }
+}
+el("sound").onclick = async () => {
+ audio ??= new AudioContext();
+ await audio.resume();
+ el("sound").hidden = true;
+};
+
+function play({header, frames, receivedAt}, pcm) {
+ stopPlayback();
+ const generation = sequence;
+ const elapsed = () => header.offset + (performance.now() - receivedAt) / 1000;
+ if (audio && pcm.byteLength >= 2) {
+ const samples = new Int16Array(pcm);
+ const buffer = audio.createBuffer(1, samples.length, header.sample_rate);
+ const channel = buffer.getChannelData(0);
+ for (let i = 0; i < samples.length; i++) channel[i] = samples[i] / 32768;
+ const offset = elapsed();
+ if (offset < buffer.duration) {
+ source = audio.createBufferSource();
+ source.buffer = buffer;
+ source.connect(audio.destination);
+ source.start(0, offset);
+ }
+ }
+ let last = -1;
+ const paint = async () => {
+ if (generation !== sequence || elapsed() >= header.duration) return;
+ const index = Math.min(frames.length - 1, Math.floor(elapsed() * header.fps));
+ if (index !== last) {
+ last = index;
+ const bitmap = await createImageBitmap(new Blob([frames[index]], {type: "image/jpeg"}));
+ if (generation === sequence) {
+ const canvas = el("screen");
+ if (canvas.width !== bitmap.width || canvas.height !== bitmap.height) {
+ canvas.width = bitmap.width;
+ canvas.height = bitmap.height;
+ }
+ canvas.getContext("2d").drawImage(bitmap, 0, 0);
+ canvas.dataset.frame = [header.request, header.chunk, index].join(".");
+ }
+ bitmap.close();
+ }
+ if (generation === sequence) animation = requestAnimationFrame(paint);
+ };
+ paint();
+}
+
+async function join() {
+ const headers = {};
+ if (producer) {
+ if (location.hash) {
+ sessionStorage.setItem("broadcastProducer", location.hash.slice(1));
+ history.replaceState(null, "", location.pathname);
+ }
+ headers.Authorization = "Bearer " + (sessionStorage.getItem("broadcastProducer") || "");
+ }
+ const role = producer ? "producer" : "viewer";
+ const response = await fetch("/tickets/" + role, {method:"POST", headers});
+ if (!response.ok) throw Error("ticket");
+ const {ticket} = await response.json();
+ socket = new WebSocket(location.origin.replace(/^http/, "ws") + "/ws");
+ socket.binaryType = "arraybuffer";
+ socket.onopen = () => socket.send(ticket);
+ socket.onmessage = ({data}) => {
+ if (typeof data === "string") {
+ const msg = JSON.parse(data);
+ if (msg.type === "show") {
+ position = msg.position;
+ el("status").textContent = states[msg.status];
+ el("position").textContent = t("Rundown", "节目单") + " · " + (position+1) + " / " + msg.count;
+ el("segment").textContent = msg.segment;
+ el("host").textContent = msg.host || "";
+ el("next").disabled = msg.status !== "live" || position+1 >= msg.count;
+ el("end").disabled = msg.status !== "live";
+ if (!msg.has_media) stopPlayback();
+ } else if (msg.type === "chunk") {
+ incoming = {header:msg, frames:[], receivedAt:performance.now()};
+ }
+ } else if (incoming) {
+ if (incoming.frames.length < incoming.header.n_frames) incoming.frames.push(data);
+ else { play(incoming, data); incoming = null; }
+ }
+ };
+ socket.onclose = () => {
+ stopPlayback();
+ el("next").disabled = el("end").disabled = true;
+ el("status").textContent = t("Disconnected. Reload to rejoin.", "连接已断开,刷新可重新加入。");
+ };
+}
+for (const type of ["next", "end"]) el(type).onclick = () => socket.send(JSON.stringify({type, position}));
+join().catch(() => { el("status").textContent = t("Unable to join this show.", "无法加入直播。"); });
diff --git a/tools/broadcast_pilot/index.html b/tools/broadcast_pilot/index.html
new file mode 100644
index 000000000..709ac0f40
--- /dev/null
+++ b/tools/broadcast_pilot/index.html
@@ -0,0 +1,20 @@
+
+
+OpenDirector Broadcast
+
+
+
+
+
diff --git a/tools/broadcast_pilot/server.py b/tools/broadcast_pilot/server.py
new file mode 100644
index 000000000..45f4422db
--- /dev/null
+++ b/tools/broadcast_pilot/server.py
@@ -0,0 +1,262 @@
+"""Local broadcast pilot. Each process owns one show and one CPU puppet connection."""
+import argparse
+import asyncio
+import hmac
+import json
+import logging
+import secrets
+import time
+from pathlib import Path
+
+from aiohttp import ClientSession, WSMsgType, web
+
+HERE = Path(__file__).parent
+LOG = logging.getLogger(__name__)
+MAX_CHUNK_BYTES = 12 * 1024 * 1024
+
+
+class Broadcast:
+ def __init__(self, upstream, rundown):
+ self.upstream = upstream
+ self.rundown = rundown
+ self.position = 0
+ self.status = "connecting"
+ self.host = None
+ self.socket = None
+ self.current = None
+ self.listeners = set()
+ self.pending = asyncio.Queue(maxsize=12)
+ self.cut = asyncio.Event()
+ self.commands = asyncio.Lock()
+
+ def notify(self):
+ for changed in self.listeners:
+ changed.set()
+
+ def clear_media(self):
+ self.current = None
+ self.cut.set()
+ self.cut = asyncio.Event()
+ while not self.pending.empty():
+ self.pending.get_nowait()
+ self.notify()
+
+ async def cue(self):
+ await self.socket.send_json({"type": "text", "text": self.rundown[self.position]})
+
+ async def command(self, name, expected_position):
+ async with self.commands:
+ if self.status != "live" or expected_position != self.position:
+ return
+ if name == "end":
+ self.status = "ended"
+ self.clear_media()
+ await self.socket.close()
+ elif name == "next" and self.position + 1 < len(self.rundown):
+ self.position += 1
+ self.notify()
+ await self.cue()
+
+ async def run(self):
+ try:
+ async with ClientSession() as client, client.ws_connect(self.upstream, heartbeat=20) as ws:
+ self.socket = ws
+ await ws.send_json({"type": "hello", "mode": "public", "video_codecs": ["jpeg"]})
+ player = asyncio.create_task(self.play(ws))
+ reader = asyncio.create_task(self.read(ws))
+ try:
+ done, _ = await asyncio.wait((reader, player), return_when=asyncio.FIRST_COMPLETED)
+ for task in done:
+ task.result()
+ finally:
+ for task in (reader, player):
+ task.cancel()
+ await asyncio.gather(reader, player, return_exceptions=True)
+ except Exception:
+ LOG.exception("CPU puppet connection ended")
+ finally:
+ self.socket = None
+ if self.status != "ended":
+ self.status = "offline"
+ self.clear_media()
+
+ async def read(self, ws):
+ header = None
+ parts = []
+ size = 0
+ async for msg in ws:
+ if msg.type == WSMsgType.TEXT:
+ event = json.loads(msg.data)
+ kind = event.get("type")
+ if kind == "status" and self.host is None:
+ self.host = event["session"]
+ self.status = "live"
+ self.notify()
+ await self.cue()
+ elif kind == "stop":
+ header = None
+ parts = []
+ self.clear_media()
+ elif kind == "error":
+ raise RuntimeError("Puppet reported a session error")
+ elif kind == "chunk":
+ if (event.get("codec") != "jpeg" or not 0 < event["n_frames"] <= 120
+ or not 0 < event["duration"] <= 10 or not 0 < event["fps"] <= 120
+ or not 8000 <= event["sample_rate"] <= 192000):
+ raise ValueError("Unsupported puppet chunk")
+ header = {key: event[key] for key in
+ ("request", "chunk", "n_frames", "fps", "sample_rate", "duration")}
+ parts = []
+ size = 0
+ elif msg.type == WSMsgType.BINARY and header is not None:
+ size += len(msg.data)
+ if size > MAX_CHUNK_BYTES:
+ raise ValueError("Puppet chunk too large")
+ parts.append(msg.data)
+ if len(parts) == header["n_frames"] + 1:
+ self.pending.put_nowait((header, parts))
+ header = None
+ parts = []
+
+ async def play(self, ws):
+ while True:
+ header, parts = await self.pending.get()
+ cut = self.cut
+ started = time.monotonic()
+ self.current = (header, parts, started)
+ self.notify()
+ key = {k: header[k] for k in ("request", "chunk")}
+ await ws.send_json({"type": "chunk_start", **key})
+ try:
+ await asyncio.wait_for(cut.wait(), max(0, started + header["duration"] - time.monotonic()))
+ except asyncio.TimeoutError:
+ if cut.is_set():
+ continue
+ # This socket is the programme consumer. It has no browser paint evidence.
+ await ws.send_json({"type": "chunk_end", **key, "painted": []})
+ self.current = None
+ self.notify()
+
+ async def publish(self, ws, changed):
+ # Each subscriber pulls the newest snapshot. A slow browser cannot queue
+ # media for the host or block a different browser.
+ previous = None
+ while True:
+ await changed.wait()
+ changed.clear()
+ current = self.current
+ await ws.send_json({"type": "show", "status": self.status, "host": self.host,
+ "position": self.position, "count": len(self.rundown),
+ "segment": self.rundown[self.position], "has_media": current is not None})
+ if current is not None and current is not previous:
+ header, parts, started = current
+ await ws.send_json({"type": "chunk", **header, "offset": time.monotonic() - started})
+ async with asyncio.timeout(5):
+ for part in parts:
+ await ws.send_bytes(part)
+ previous = current
+
+
+def create_app(show, origin, producer_key):
+ tickets = {}
+ app = web.Application(client_max_size=4096)
+
+ def same_origin(request):
+ if request.headers.get("Origin") != origin or request.host != origin.split("://", 1)[1]:
+ raise web.HTTPForbidden()
+
+ async def page(request):
+ filename = "client.js" if request.path == "/client.js" else "index.html"
+ return web.FileResponse(HERE / filename, headers={
+ "Cache-Control": "no-store", "Referrer-Policy": "no-referrer",
+ "Content-Security-Policy": "default-src 'self'; script-src 'self'; style-src 'unsafe-inline'; "
+ "img-src blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'",
+ })
+
+ async def issue(request):
+ same_origin(request)
+ role = request.match_info["role"]
+ if role == "producer" and not hmac.compare_digest(
+ request.headers.get("Authorization", "").encode(), f"Bearer {producer_key}".encode()):
+ raise web.HTTPForbidden()
+ now = time.monotonic()
+ for token in [token for token, (_, expiry) in tickets.items() if expiry <= now]:
+ del tickets[token]
+ if len(tickets) >= 128:
+ raise web.HTTPTooManyRequests()
+ token = secrets.token_urlsafe(32)
+ tickets[token] = (role, now + 30)
+ return web.json_response({"ticket": token}, headers={"Cache-Control": "no-store"})
+
+ async def socket(request):
+ same_origin(request)
+ ws = web.WebSocketResponse(max_msg_size=2048, heartbeat=20)
+ await ws.prepare(request)
+ try:
+ first = await ws.receive(timeout=5)
+ except asyncio.TimeoutError:
+ await ws.close(code=1008)
+ return ws
+ entry = tickets.pop(first.data, None) if first.type == WSMsgType.TEXT else None
+ if not entry or entry[1] <= time.monotonic():
+ await ws.close(code=1008)
+ return ws
+ role = entry[0]
+ changed = asyncio.Event()
+ show.listeners.add(changed)
+ changed.set()
+
+ async def receive():
+ async for msg in ws:
+ if role != "producer" or msg.type != WSMsgType.TEXT:
+ await ws.close(code=1008)
+ return
+ try:
+ command = json.loads(msg.data)
+ await show.command(command["type"], command["position"])
+ except (ValueError, KeyError, TypeError):
+ await ws.close(code=1008)
+ return
+
+ tasks = [asyncio.create_task(receive()), asyncio.create_task(show.publish(ws, changed))]
+ try:
+ done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
+ for task in done:
+ task.result()
+ except (ConnectionResetError, TimeoutError):
+ pass # A departed or stalled subscriber only releases its own socket.
+ finally:
+ show.listeners.discard(changed)
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ return ws
+
+ async def lifetime(_):
+ task = asyncio.create_task(show.run())
+ try:
+ yield
+ finally:
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+ app.cleanup_ctx.append(lifetime)
+ for path in ("/producer", "/viewer", "/client.js"):
+ app.router.add_get(path, page)
+ app.router.add_post("/tickets/{role:producer|viewer}", issue)
+ app.router.add_get("/ws", socket)
+ return app
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--port", type=int, default=8210)
+ parser.add_argument("--puppet-port", type=int, default=8201)
+ parser.add_argument("--segment", action="append", help="Puppet cue for one rundown segment, in order")
+ args = parser.parse_args()
+ origin = f"http://127.0.0.1:{args.port}"
+ key = secrets.token_urlsafe(32)
+ rundown = args.segment or ["Open the book discussion", "Introduce the first reading", "Close the show"]
+ print(f"Producer: {origin}/producer#{key}\nViewer: {origin}/viewer", flush=True)
+ web.run_app(create_app(Broadcast(f"ws://127.0.0.1:{args.puppet_port}/ws", rundown), origin, key),
+ host="127.0.0.1", port=args.port, access_log=None)
diff --git a/tools/broadcast_pilot/test_pilot.py b/tools/broadcast_pilot/test_pilot.py
new file mode 100644
index 000000000..8c991847b
--- /dev/null
+++ b/tools/broadcast_pilot/test_pilot.py
@@ -0,0 +1,154 @@
+import asyncio
+import unittest
+import time
+from unittest.mock import patch
+
+from aiohttp import WSServerHandshakeError, WSMsgType, web
+from aiohttp.test_utils import TestClient, TestServer, unused_port
+
+from server import Broadcast, create_app
+
+
+class PilotTest(unittest.IsolatedAsyncioTestCase):
+ async def asyncSetUp(self):
+ self.connections = 0
+ self.cues = []
+ self.ready = asyncio.Event()
+ self.closed = asyncio.Event()
+
+ async def puppet(request):
+ ws = web.WebSocketResponse()
+ await ws.prepare(request)
+ self.connections += 1
+ self.assertEqual(await ws.receive_json(), {"type": "hello", "mode": "public", "video_codecs": ["jpeg"]})
+ self.puppet = ws
+ await ws.send_json({"type": "status", "session": "test-host"})
+ try:
+ async for msg in ws:
+ data = msg.json()
+ if data["type"] == "text":
+ self.cues.append(data["text"])
+ self.ready.set()
+ finally:
+ self.closed.set()
+ return ws
+
+ upstream = web.Application()
+ upstream.router.add_get("/ws", puppet)
+ server = TestServer(upstream)
+ await server.start_server()
+ self.addAsyncCleanup(server.close)
+ port = unused_port()
+ self.origin = f"http://127.0.0.1:{port}"
+ self.show = Broadcast(str(server.make_url("/ws")).replace("http:", "ws:"), ["Opening", "Reading"])
+ self.client = TestClient(TestServer(create_app(self.show, self.origin, "test-key"), port=port))
+ await self.client.start_server()
+ self.addAsyncCleanup(self.client.close)
+ await asyncio.wait_for(self.ready.wait(), 2)
+
+ async def ticket(self, role="viewer"):
+ headers = {"Origin": self.origin}
+ if role == "producer":
+ headers["Authorization"] = "Bearer test-key"
+ result = await self.client.post("/tickets/" + role, headers=headers)
+ self.assertEqual(result.status, 200)
+ return (await result.json())["ticket"]
+
+ async def attach(self, ticket):
+ ws = await self.client.ws_connect("/ws", origin=self.origin)
+ await ws.send_str(ticket)
+ return ws
+
+ async def test_origin_and_single_use(self):
+ for origin in ("http://example.invalid", self.origin + ".invalid", "null", ""):
+ result = await self.client.post("/tickets/viewer", headers={"Origin": origin})
+ self.assertEqual(result.status, 403)
+ with self.assertRaises(WSServerHandshakeError):
+ await self.client.ws_connect("/ws", origin=origin)
+ result = await self.client.post("/tickets/producer", headers={"Origin": self.origin})
+ self.assertEqual(result.status, 403)
+ token = await self.ticket()
+ a, b = await asyncio.gather(self.attach(token), self.attach(token))
+ replies = await asyncio.gather(a.receive(), b.receive())
+ self.assertCountEqual([m.type for m in replies], [WSMsgType.TEXT, WSMsgType.CLOSE])
+ self.assertEqual(next(m.data for m in replies if m.type == WSMsgType.CLOSE), 1008)
+
+ async def test_expired_ticket(self):
+ with patch("server.time", wraps=time) as clock:
+ clock.monotonic.return_value = 100
+ ticket = await self.ticket()
+ clock.monotonic.return_value = 130
+ ws = await self.attach(ticket)
+ self.assertEqual((await ws.receive()).data, 1008)
+
+ async def test_viewer_cannot_direct_and_refresh_preserves_show(self):
+ viewer = await self.attach(await self.ticket())
+ self.assertEqual((await viewer.receive_json())["segment"], "Opening")
+ await viewer.send_json({"type": "end", "position": 0})
+ self.assertEqual((await viewer.receive()).data, 1008)
+ producer = await self.attach(await self.ticket("producer"))
+ await producer.receive_json()
+ await producer.send_json({"type": "next", "position": 0})
+ self.assertEqual((await producer.receive_json())["segment"], "Reading")
+ await producer.close()
+ viewer = await self.attach(await self.ticket())
+ self.assertEqual((await viewer.receive_json())["position"], 1)
+ producer = await self.attach(await self.ticket("producer"))
+ self.assertEqual((await producer.receive_json())["host"], "test-host")
+ self.assertEqual(self.connections, 1)
+ self.assertEqual(self.cues, ["Opening", "Reading"])
+ await producer.send_json({"type": "end", "position": 1})
+ await asyncio.wait_for(self.closed.wait(), 2)
+ self.assertEqual((await viewer.receive_json())["status"], "ended")
+
+ async def test_late_join_starts_inside_same_chunk(self):
+ first = await self.attach(await self.ticket())
+ await first.receive_json()
+ header = dict(type="chunk", request=3, chunk=1, n_frames=1, codec="jpeg",
+ sample_rate=16000, fps=1, duration=2)
+ await self.puppet.send_json(header)
+ await self.puppet.send_bytes(b"jpeg")
+ await self.puppet.send_bytes(b"pcm")
+ await first.receive_json()
+ first_chunk = await first.receive_json()
+ late = await self.attach(await self.ticket())
+ await late.receive_json()
+ late_chunk = await late.receive_json()
+ self.assertGreater(late_chunk["offset"], first_chunk["offset"])
+ self.assertEqual((late_chunk["request"], late_chunk["chunk"]), (3, 1))
+ await first.close()
+ self.assertEqual(await late.receive_bytes(), b"jpeg")
+ self.assertEqual(await late.receive_bytes(), b"pcm")
+ self.assertEqual(self.connections, 1)
+ self.assertFalse(self.closed.is_set())
+
+ async def test_host_loss_leaves_existing_and_new_viewers_offline(self):
+ ws = await self.attach(await self.ticket())
+ await ws.receive_json()
+ await self.puppet.close()
+ state = await asyncio.wait_for(ws.receive_json(), 2)
+ self.assertEqual(state["status"], "offline")
+ late = await self.attach(await self.ticket())
+ self.assertEqual((await late.receive_json())["status"], "offline")
+ self.assertEqual(self.connections, 1)
+
+ async def test_partial_chunk_is_discarded_on_puppet_stop(self):
+ ws = await self.attach(await self.ticket())
+ await ws.receive_json()
+ header = dict(type="chunk", request=1, chunk=0, n_frames=2, codec="jpeg",
+ sample_rate=16000, fps=2, duration=1)
+ await self.puppet.send_json(header)
+ await self.puppet.send_bytes(b"old")
+ await self.puppet.send_json({"type": "stop"})
+ await self.puppet.send_json(dict(header, request=2))
+ for part in (b"first", b"second", b"pcm"):
+ await self.puppet.send_bytes(part)
+ async with asyncio.timeout(2):
+ while (state := await ws.receive_json())["type"] != "chunk":
+ self.assertEqual(state["type"], "show")
+ self.assertEqual(state["request"], 2)
+ self.assertEqual([await ws.receive_bytes() for _ in range(3)], [b"first", b"second", b"pcm"])
+
+
+if __name__ == "__main__":
+ unittest.main()
From f9d8e1fdba747a79acf2e7f6a1b6765f1d6b190e Mon Sep 17 00:00:00 2001
From: maithilijoshi20 <97733343+maithilijoshi20@users.noreply.github.com>
Date: Mon, 30 Nov 2026 16:41:14 +0900
Subject: [PATCH 2/3] fix(broadcast): Start audio at the current chunk position
## summary
Retain the current PCM until the viewer enables sound and use the video clock to start the remaining audio. Exercise the final chunk in Chromium.
Signed-off-by: maithilijoshi20 <97733343+maithilijoshi20@users.noreply.github.com>
---
tools/broadcast_pilot/README.md | 8 ++--
tools/broadcast_pilot/check_audio.py | 67 ++++++++++++++++++++++++++++
tools/broadcast_pilot/client.js | 37 +++++++++------
3 files changed, 95 insertions(+), 17 deletions(-)
create mode 100644 tools/broadcast_pilot/check_audio.py
diff --git a/tools/broadcast_pilot/README.md b/tools/broadcast_pilot/README.md
index 84258f5ad..eb4545a5a 100644
--- a/tools/broadcast_pilot/README.md
+++ b/tools/broadcast_pilot/README.md
@@ -29,7 +29,7 @@ python tools/broadcast_pilot/server.py \
```
Open the producer URL printed in the terminal. Share the viewer URL with another
-browser on the same machine. Use **Enable audio** to hear subsequent puppet audio.
+browser on the same machine. Use **Enable audio** to hear puppet audio from the current playback position.
The offline voice produces synthetic sounds. Choose **Next segment** to cue the
host or **End show** to close its connection. Restart the pilot for a new show.
@@ -67,15 +67,17 @@ For the browser check, start a fresh show with at least two segments and set
pip install playwright
playwright install --with-deps chromium
python tools/broadcast_pilot/check_browsers.py
+python tools/broadcast_pilot/check_audio.py
```
The check uses independent Chromium clients, verifies that puppet frames advance
after a console refresh and a viewer departure, and compares the host ID and
-rundown across clients.
+rundown across clients. The standalone audio check serves a single fixture chunk and verifies
+that enabling sound during playback starts audible samples at the live offset.
## 本地试播
按上面的命令先启动 CPU 木偶服务,再启动导播程序。使用终端输出的私有导播链接
-进入导播台,将观众链接交给同机的其他浏览器。点击「开启声音」可收听后续音频。
+进入导播台,将观众链接交给同机的其他浏览器。点击「开启声音」可从当前播放位置开始收听音频。
「下一环节」切换所有观众看到的节目单位置;「结束直播」关闭主播连接。刷新导播台
或关闭一个观众页,其他观众仍可继续观看。每次试播只有一个主播,离线合成音不包含真实语音。
diff --git a/tools/broadcast_pilot/check_audio.py b/tools/broadcast_pilot/check_audio.py
new file mode 100644
index 000000000..07e2fcd79
--- /dev/null
+++ b/tools/broadcast_pilot/check_audio.py
@@ -0,0 +1,67 @@
+"""Check enabling audio partway through the final chunk in Chromium."""
+import base64
+import json
+import math
+import re
+import struct
+from pathlib import Path
+
+from playwright.sync_api import expect, sync_playwright
+
+
+def main():
+ root = Path(__file__).parent
+ origin = "http://127.0.0.1:8210"
+ with sync_playwright() as playwright:
+ browser = playwright.chromium.launch()
+ page = browser.new_page(locale="en-US")
+ page.route(origin + "/viewer", lambda route: route.fulfill(path=root / "index.html"))
+ page.route(origin + "/client.js", lambda route: route.fulfill(path=root / "client.js"))
+ page.route(origin + "/tickets/viewer", lambda route: route.fulfill(json={"ticket": "fixture"}))
+ jpeg = base64.b64decode(page.evaluate("document.createElement('canvas').toDataURL('image/jpeg').split(',')[1]"))
+ rate, seconds = 8000, 6
+ pcm = b"".join(struct.pack(" {
+ if (!window.analyser) return false;
+ const samples = new Float32Array(analyser.fftSize);
+ analyser.getFloatTimeDomainData(samples);
+ return samples.some(value => Math.abs(value) > 0.1);
+ }""", timeout=2000)
+ offsets = page.evaluate("window.audioStarts")
+ assert len(offsets) == 1 and 2 <= offsets[0] < seconds, offsets
+ print(f"Final chunk produced audio at {offsets[0]:.3f}s after joining at 1s.")
+ browser.close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/broadcast_pilot/client.js b/tools/broadcast_pilot/client.js
index f8785652c..cf29e5fac 100644
--- a/tools/broadcast_pilot/client.js
+++ b/tools/broadcast_pilot/client.js
@@ -16,35 +16,44 @@ el("screen").setAttribute("aria-label", t("Live puppet", "实时木偶"));
el("controls").hidden = !producer;
el("status").textContent = states.connecting;
-let audio, source, animation, sequence = 0, incoming, socket, position;
+let audio, pendingAudio, source, animation, sequence = 0, incoming, socket, position;
function stopPlayback() {
sequence++;
+ pendingAudio = null;
cancelAnimationFrame(animation);
if (source) { source.stop(); source = null; }
}
el("sound").onclick = async () => {
audio ??= new AudioContext();
await audio.resume();
+ startAudio();
el("sound").hidden = true;
};
+function startAudio() {
+ if (audio?.state !== "running" || !pendingAudio) return;
+ const {header, pcm, elapsed} = pendingAudio;
+ pendingAudio = null;
+ if (pcm.byteLength < 2) return;
+ const samples = new Int16Array(pcm);
+ const buffer = audio.createBuffer(1, samples.length, header.sample_rate);
+ const channel = buffer.getChannelData(0);
+ for (let i = 0; i < samples.length; i++) channel[i] = samples[i] / 32768;
+ const offset = elapsed();
+ const remaining = Math.min(header.duration, buffer.duration) - offset;
+ if (remaining <= 0) return;
+ source = audio.createBufferSource();
+ source.buffer = buffer;
+ source.connect(audio.destination);
+ source.start(0, offset, remaining);
+}
+
function play({header, frames, receivedAt}, pcm) {
stopPlayback();
const generation = sequence;
const elapsed = () => header.offset + (performance.now() - receivedAt) / 1000;
- if (audio && pcm.byteLength >= 2) {
- const samples = new Int16Array(pcm);
- const buffer = audio.createBuffer(1, samples.length, header.sample_rate);
- const channel = buffer.getChannelData(0);
- for (let i = 0; i < samples.length; i++) channel[i] = samples[i] / 32768;
- const offset = elapsed();
- if (offset < buffer.duration) {
- source = audio.createBufferSource();
- source.buffer = buffer;
- source.connect(audio.destination);
- source.start(0, offset);
- }
- }
+ pendingAudio = {header, pcm, elapsed};
+ startAudio();
let last = -1;
const paint = async () => {
if (generation !== sequence || elapsed() >= header.duration) return;
From 491fd019b5c846d7d279777b99f4c1cdecd1642c Mon Sep 17 00:00:00 2001
From: maithilijoshi20 <97733343+maithilijoshi20@users.noreply.github.com>
Date: Mon, 30 Nov 2026 17:25:11 +0900
Subject: [PATCH 3/3] chore(broadcast): Remove redundant transport comments
Signed-off-by: maithilijoshi20 <97733343+maithilijoshi20@users.noreply.github.com>
---
tools/broadcast_pilot/server.py | 5 +----
1 file changed, 1 insertion(+), 4 deletions(-)
diff --git a/tools/broadcast_pilot/server.py b/tools/broadcast_pilot/server.py
index 45f4422db..b5bd1c17b 100644
--- a/tools/broadcast_pilot/server.py
+++ b/tools/broadcast_pilot/server.py
@@ -132,14 +132,11 @@ async def play(self, ws):
except asyncio.TimeoutError:
if cut.is_set():
continue
- # This socket is the programme consumer. It has no browser paint evidence.
await ws.send_json({"type": "chunk_end", **key, "painted": []})
self.current = None
self.notify()
async def publish(self, ws, changed):
- # Each subscriber pulls the newest snapshot. A slow browser cannot queue
- # media for the host or block a different browser.
previous = None
while True:
await changed.wait()
@@ -224,7 +221,7 @@ async def receive():
for task in done:
task.result()
except (ConnectionResetError, TimeoutError):
- pass # A departed or stalled subscriber only releases its own socket.
+ pass
finally:
show.listeners.discard(changed)
for task in tasks: