Repository navigation
Add a shared CPU puppet broadcast pilot #599
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
maithilijoshi20
wants to merge
4
commits into
ThinkFlowLab:main
Choose a base branch
from
maithilijoshi20:rfc11195-broadcast-pilot
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
27336b1
feat(broadcast): Share one CPU puppet across the pilot console and vi…
maithilijoshi20 f9d8e1f
fix(broadcast): Start audio at the current chunk position
maithilijoshi20 6c0c166
Merge upstream main into the broadcast pilot
maithilijoshi20 491fd01
chore(broadcast): Remove redundant transport comments
maithilijoshi20 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| # 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 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. | ||
|
|
||
| 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 | ||
| 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. The standalone audio check serves a single fixture chunk and verifies | ||
| that enabling sound during playback starts audible samples at the live offset. | ||
|
|
||
| ## 本地试播 | ||
|
|
||
| 按上面的命令先启动 CPU 木偶服务,再启动导播程序。使用终端输出的私有导播链接 | ||
| 进入导播台,将观众链接交给同机的其他浏览器。点击「开启声音」可从当前播放位置开始收听音频。 | ||
| 「下一环节」切换所有观众看到的节目单位置;「结束直播」关闭主播连接。刷新导播台 | ||
| 或关闭一个观众页,其他观众仍可继续观看。每次试播只有一个主播,离线合成音不包含真实语音。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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("<h", round(8192 * math.sin(2 * math.pi * 440 * i / rate))) | ||
| for i in range(rate * seconds)) | ||
|
|
||
| def attach(socket): | ||
| def send_final_chunk(ticket): | ||
| assert ticket == "fixture" | ||
| socket.send(json.dumps(dict(type="show", status="live", host="fixture", position=0, | ||
| count=1, segment="Final segment", has_media=True))) | ||
| socket.send(json.dumps(dict(type="chunk", request=1, chunk=0, n_frames=seconds, | ||
| fps=1, sample_rate=rate, duration=seconds, offset=1))) | ||
| for _ in range(seconds): | ||
| socket.send(jpeg) | ||
| socket.send(pcm) | ||
| socket.on_message(send_final_chunk) | ||
|
|
||
| page.route_web_socket("**/ws", attach) | ||
| page.add_init_script(""" | ||
| window.audioStarts = []; | ||
| const start = AudioBufferSourceNode.prototype.start; | ||
| AudioBufferSourceNode.prototype.start = function(when, offset, ...rest) { | ||
| const analyser = this.context.createAnalyser(); | ||
| this.connect(analyser); | ||
| window.analyser = analyser; | ||
| window.audioStarts.push(offset); | ||
| return start.call(this, when, offset, ...rest); | ||
| }; | ||
| """) | ||
| page.goto(origin + "/viewer") | ||
| expect(page.locator("canvas")).to_have_attribute("data-frame", re.compile(r"1\.0\.[2-5]")) | ||
| assert page.evaluate("window.audioStarts.length") == 0 | ||
| page.get_by_role("button", name="Enable audio").click() | ||
| page.wait_for_function("""() => { | ||
| 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| 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, 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; | ||
| pendingAudio = {header, pcm, elapsed}; | ||
| startAudio(); | ||
| 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.", "无法加入直播。"); }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| <!doctype html> | ||
| <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"> | ||
| <title>OpenDirector Broadcast</title> | ||
| <style> | ||
| :root{color-scheme:dark;font:16px system-ui,sans-serif;background:#161916;color:#f1eee5} | ||
| *{box-sizing:border-box}body{max-width:880px;margin:auto;padding:clamp(16px,4vw,48px)} | ||
| header,footer,nav{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap} | ||
| header{padding-bottom:14px;border-bottom:1px solid #53584c}h1{font:500 clamp(24px,4vw,36px) Georgia,serif;margin:0} | ||
| main{padding-top:18px}canvas{width:100%;height:min(55vh,480px);background:#0c100f;object-fit:contain} | ||
| h2{font:500 24px Georgia,serif;margin:7px 0}p,small{color:#c0c5b6}footer{margin-top:18px} | ||
| button,a{color:inherit;font:inherit}button{border:1px solid #707564;border-radius:5px;background:#262c24;padding:8px 12px;cursor:pointer} | ||
| button:disabled{opacity:.45}button.primary{background:#d4e5bb;color:#172114}a{color:#d4e5bb} | ||
| [hidden]{display:none!important}#status{font-weight:600} | ||
| </style></head><body> | ||
| <header><h1 id="title">OpenDirector</h1><span id="status" role="status"></span></header> | ||
| <main><canvas width="864" height="480" id="screen"></canvas> | ||
| <p id="position"></p><h2 id="segment"></h2><small id="host"></small> | ||
| <footer><nav id="controls" hidden><button id="next" class="primary" disabled></button><button id="end" disabled></button> | ||
| <a href="/viewer" target="_blank" rel="noopener" id="viewer"></a></nav> | ||
| <button id="sound"></button></footer></main><script src="/client.js" defer></script></body></html> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.