- hub: FastAPI backend (MCP server, ADB LAN controller, bridge, storage) - hub/web: Vue 3 admin console (device manager, screen mirror, chat workbench) - android: Kotlin shell app with WebView stage, OTA, telemetry, keep-alive - protocol: architecture, MCP schema, and WebSocket protocol specs
602 lines
25 KiB
Python
602 lines
25 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import time
|
|
from pathlib import Path
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app.main import create_app
|
|
|
|
|
|
def test_device_ws_config_interaction_and_lan_guard(tmp_path: Path) -> None:
|
|
app = create_app(str(tmp_path / "test.db"))
|
|
with TestClient(app) as client:
|
|
resp = client.get("/health")
|
|
assert resp.status_code == 200
|
|
assert resp.json()["status"] == "ok"
|
|
|
|
with client.websocket_connect("/ws/device/android11-test") as ws:
|
|
cfg_frame = json.loads(ws.receive_text())
|
|
assert cfg_frame["type"] == "config.push"
|
|
assert "repair_ai" in cfg_frame["payload"]
|
|
|
|
ws.send_text(
|
|
json.dumps(
|
|
{
|
|
"type": "device.hello",
|
|
"payload": {
|
|
"device_id": "android11-test",
|
|
"device_name": "客厅 Android 11",
|
|
"model": "Mi 10",
|
|
"android_sdk": 30,
|
|
"android_release": "11",
|
|
"capabilities": ["basic", "root"],
|
|
"display_profile": {
|
|
"device_type": "phone",
|
|
"orientation": "portrait",
|
|
"viewport_css_w": 392,
|
|
"viewport_css_h": 850,
|
|
"dpr": 2.75,
|
|
"webview_version": "114.0.5735.196",
|
|
},
|
|
},
|
|
}
|
|
)
|
|
)
|
|
cfg_frame2 = json.loads(ws.receive_text())
|
|
assert cfg_frame2["type"] == "config.push"
|
|
|
|
devs = client.get("/api/admin/devices").json()["devices"]
|
|
assert len(devs) == 1
|
|
assert devs[0]["online"] is True
|
|
assert devs[0]["display_profile"]["viewport_css_w"] == 392
|
|
|
|
ws.send_text(
|
|
json.dumps(
|
|
{
|
|
"type": "interaction.reply",
|
|
"payload": {
|
|
"interaction_id": "int_123",
|
|
"selected_preset_id": "ack",
|
|
"selected_label": "确认收到",
|
|
"custom_text": None,
|
|
},
|
|
}
|
|
)
|
|
)
|
|
time.sleep(0.05)
|
|
evts = client.get("/api/admin/events").json()["events"]
|
|
assert len(evts) == 1
|
|
assert evts[0]["event_type"] == "user_interaction_reply"
|
|
assert evts[0]["payload"]["selected_preset_id"] == "ack"
|
|
|
|
# LAN-only ADB guard MUST reject public forwarded IP
|
|
r_pub = client.post(
|
|
"/api/lan-debug/android11-test/action",
|
|
json={"action": "status"},
|
|
headers={"X-Forwarded-For": "8.8.8.8"},
|
|
)
|
|
assert r_pub.status_code == 403
|
|
|
|
# LAN request blocked until global switch is turned on
|
|
r_disabled = client.post("/api/lan-debug/android11-test/action", json={"action": "status"})
|
|
assert r_disabled.status_code == 403
|
|
|
|
|
|
def test_mcp_streamable_http_tools_list(tmp_path: Path) -> None:
|
|
app = create_app(str(tmp_path / "mcp_test.db"))
|
|
with TestClient(app) as client:
|
|
headers = {
|
|
"Accept": "application/json, text/event-stream",
|
|
"Content-Type": "application/json",
|
|
}
|
|
init_req = {
|
|
"jsonrpc": "2.0",
|
|
"id": 1,
|
|
"method": "initialize",
|
|
"params": {
|
|
"protocolVersion": "2025-03-26",
|
|
"capabilities": {},
|
|
"clientInfo": {"name": "pytest-client", "version": "1.0"},
|
|
},
|
|
}
|
|
r1 = client.post("/mcp/", json=init_req, headers=headers)
|
|
assert r1.status_code == 200
|
|
body1 = r1.json()
|
|
assert body1["result"]["serverInfo"]["name"] == "PulseWall Hub"
|
|
|
|
tools_req = {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}
|
|
r2 = client.post("/mcp/", json=tools_req, headers=headers)
|
|
assert r2.status_code == 200
|
|
tool_names = {t["name"] for t in r2.json()["result"]["tools"]}
|
|
assert {
|
|
"list_devices",
|
|
"get_device_status",
|
|
"push_feed_item",
|
|
"trigger_alert",
|
|
"render_page",
|
|
"reply_clarification",
|
|
"get_pending_events",
|
|
"lan_adb_action",
|
|
}.issubset(tool_names)
|
|
|
|
|
|
def test_render_clarification_bidirectional_flow(tmp_path: Path) -> None:
|
|
import threading
|
|
|
|
app = create_app(str(tmp_path / "clarify.db"))
|
|
with TestClient(app) as client:
|
|
with client.websocket_connect("/ws/device/tablet-01") as ws:
|
|
# Consume initial config.push
|
|
assert json.loads(ws.receive_text())["type"] == "config.push"
|
|
|
|
# Trigger render from a background thread (simulating upstream AI MCP/Admin call)
|
|
result_box: dict = {}
|
|
|
|
def do_render() -> None:
|
|
r = client.post("/api/admin/test/render", json={"device_id": "tablet-01"})
|
|
result_box["status_code"] = r.status_code
|
|
result_box["body"] = r.json()
|
|
|
|
t = threading.Thread(target=do_render)
|
|
t.start()
|
|
|
|
# Mock Android receives render.apply and returns needs_clarification from Repair AI
|
|
render_frame = json.loads(ws.receive_text())
|
|
assert render_frame["type"] == "render.apply"
|
|
task_id = render_frame["payload"]["task_id"]
|
|
snapshot_id = render_frame["payload"]["snapshot_id"]
|
|
|
|
ws.send_text(
|
|
json.dumps(
|
|
{
|
|
"type": "render.result",
|
|
"payload": {
|
|
"task_id": task_id,
|
|
"snapshot_id": snapshot_id,
|
|
"trigger": "initial_render",
|
|
"status": "needs_clarification",
|
|
"attempts": 1,
|
|
"clarification_questions": [
|
|
{"field": "server.gpu_temp", "question": "缺少 gpu_temp 字段,请问应显示什么?"}
|
|
],
|
|
"errors": ["ReferenceError: gpu_temp is not defined"],
|
|
},
|
|
}
|
|
)
|
|
)
|
|
t.join(timeout=5)
|
|
assert result_box["status_code"] == 200
|
|
assert result_box["body"]["status"] == "needs_clarification"
|
|
assert len(result_box["body"]["clarification_questions"]) == 1
|
|
|
|
# Verify reverse event was also persisted for upstream plugins / polling
|
|
evts = client.get("/api/admin/events").json()["events"]
|
|
assert any(e["event_type"] == "repair_data_clarification" for e in evts)
|
|
|
|
|
|
def test_ota_latest_download_and_push(tmp_path: Path) -> None:
|
|
releases = tmp_path / "releases"
|
|
releases.mkdir()
|
|
apk_bytes = b"PK\x03\x04fake-apk-payload"
|
|
(releases / "pulsewall-latest.apk").write_bytes(apk_bytes)
|
|
(releases / "latest.json").write_text(
|
|
json.dumps(
|
|
{
|
|
"version_code": 2,
|
|
"version_name": "0.1.1",
|
|
"filename": "pulsewall-latest.apk",
|
|
"size_bytes": len(apk_bytes),
|
|
"sha256": "deadbeef",
|
|
"changelog": "测试 OTA 更新",
|
|
}
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
|
|
app = create_app(str(tmp_path / "ota.db"), releases_dir=releases)
|
|
with TestClient(app) as client:
|
|
r = client.get("/api/ota/latest")
|
|
assert r.status_code == 200
|
|
data = r.json()
|
|
assert data["available"] is True
|
|
assert data["version_code"] == 2
|
|
assert data["download_path"] == "/api/ota/download/pulsewall-latest.apk"
|
|
|
|
dl = client.get(data["download_path"])
|
|
assert dl.status_code == 200
|
|
assert dl.content == apk_bytes
|
|
|
|
with client.websocket_connect("/ws/device/ota-phone") as ws:
|
|
assert json.loads(ws.receive_text())["type"] == "config.push"
|
|
push_res = client.post("/api/admin/ota/push").json()
|
|
assert push_res["pushed_devices"] == 1
|
|
ota_frame = json.loads(ws.receive_text())
|
|
assert ota_frame["type"] == "ota.available"
|
|
assert ota_frame["payload"]["version_code"] == 2
|
|
|
|
|
|
def test_ai_config_persistence_and_auto_push_to_new_and_existing_devices(tmp_path: Path) -> None:
|
|
db_file = str(tmp_path / "cfg_persist.db")
|
|
|
|
# 1. Save AI config in Hub instance #1 and verify active devices get immediate live sync
|
|
app1 = create_app(db_file)
|
|
with TestClient(app1) as client1:
|
|
with client1.websocket_connect("/ws/device/old-box") as ws_old:
|
|
init_cfg = json.loads(ws_old.receive_text())
|
|
assert init_cfg["type"] == "config.push"
|
|
assert init_cfg["payload"]["repair_ai"]["enabled"] is False
|
|
|
|
# Admin updates & saves AI config -> pushed live to online device
|
|
save_res = client1.put(
|
|
"/api/admin/config",
|
|
json={
|
|
"repair_ai": {
|
|
"enabled": True,
|
|
"base_url": "https://api.deepseek.com/v1",
|
|
"api_key": "sk-live-secret",
|
|
"model": "deepseek-chat",
|
|
"timeout_sec": 30,
|
|
"max_retries": 3,
|
|
"runtime_cooldown_sec": 20,
|
|
},
|
|
"telemetry_interval_sec": 10,
|
|
"theme": "dark-glass",
|
|
"lan_debug_enabled": False,
|
|
"auth_token": "",
|
|
},
|
|
)
|
|
assert save_res.status_code == 200
|
|
assert save_res.json()["pushed_devices"] == 1
|
|
|
|
pushed_frame = json.loads(ws_old.receive_text())
|
|
assert pushed_frame["type"] == "config.push"
|
|
assert pushed_frame["payload"]["repair_ai"]["enabled"] is True
|
|
assert pushed_frame["payload"]["repair_ai"]["model"] == "deepseek-chat"
|
|
assert pushed_frame["payload"]["repair_ai"]["api_key"] == "sk-live-secret"
|
|
|
|
# 2. Simulate Hub restart (instance #2 using same SQLite DB):
|
|
# both reconnecting old device AND brand-new device auto-receive persisted AI config!
|
|
app2 = create_app(db_file)
|
|
with TestClient(app2) as client2:
|
|
with client2.websocket_connect("/ws/device/old-box") as ws_old_reconn:
|
|
f1 = json.loads(ws_old_reconn.receive_text())
|
|
assert f1["type"] == "config.push"
|
|
assert f1["payload"]["repair_ai"]["base_url"] == "https://api.deepseek.com/v1"
|
|
assert f1["payload"]["repair_ai"]["model"] == "deepseek-chat"
|
|
|
|
with client2.websocket_connect("/ws/device/brand-new-tablet") as ws_new:
|
|
f2 = json.loads(ws_new.receive_text())
|
|
assert f2["type"] == "config.push"
|
|
assert f2["payload"]["repair_ai"]["enabled"] is True
|
|
assert f2["payload"]["repair_ai"]["api_key"] == "sk-live-secret"
|
|
|
|
|
|
def test_per_device_ai_override_isolation_and_hub_mcp_chat_agent(tmp_path: Path) -> None:
|
|
import asyncio
|
|
import httpx
|
|
from app.admin.chat_agent import HubMcpChatAgent
|
|
|
|
db_file = str(tmp_path / "per_dev_chat.db")
|
|
app = create_app(db_file)
|
|
|
|
with TestClient(app) as client:
|
|
# 1. Connect two different devices: tv-box and tablet
|
|
with client.websocket_connect("/ws/device/tv-box") as ws_tv, client.websocket_connect("/ws/device/tablet") as ws_tab:
|
|
assert json.loads(ws_tv.receive_text())["type"] == "config.push"
|
|
assert json.loads(ws_tab.receive_text())["type"] == "config.push"
|
|
|
|
ws_tv.send_text(json.dumps({"type": "device.hello", "payload": {"device_name": "客厅机顶盒", "model": "TVBox", "display_profile": {"device_type": "tv", "viewport_css_w": 960, "viewport_css_h": 540}}}))
|
|
assert json.loads(ws_tv.receive_text())["type"] == "config.push"
|
|
ws_tab.send_text(json.dumps({"type": "device.hello", "payload": {"device_name": "桌面平板", "model": "Pad", "display_profile": {"device_type": "tablet", "viewport_css_w": 1200, "viewport_css_h": 800}}}))
|
|
assert json.loads(ws_tab.receive_text())["type"] == "config.push"
|
|
|
|
# 2. Set device-specific AI config ONLY for tv-box
|
|
r = client.put(
|
|
"/api/admin/devices/tv-box/repair-ai",
|
|
json={
|
|
"use_custom": True,
|
|
"repair_ai": {
|
|
"enabled": True,
|
|
"base_url": "http://192.168.1.50:11434/v1",
|
|
"api_key": "ollama-local",
|
|
"model": "qwen2.5-coder:7b",
|
|
"timeout_sec": 30,
|
|
"max_retries": 2,
|
|
"runtime_cooldown_sec": 15,
|
|
},
|
|
},
|
|
)
|
|
assert r.status_code == 200
|
|
assert r.json()["pushed_online"] is True
|
|
|
|
# Only tv-box receives the custom model
|
|
tv_cfg = json.loads(ws_tv.receive_text())
|
|
assert tv_cfg["type"] == "config.push"
|
|
assert tv_cfg["payload"]["repair_ai"]["model"] == "qwen2.5-coder:7b"
|
|
|
|
# 3. Updating global default config keeps tv-box on its custom AI while pushing global default to tablet
|
|
client.put(
|
|
"/api/admin/config",
|
|
json={
|
|
"repair_ai": {
|
|
"enabled": True,
|
|
"base_url": "https://api.openai.com/v1",
|
|
"api_key": "sk-global",
|
|
"model": "gpt-4o-mini",
|
|
"timeout_sec": 30,
|
|
"max_retries": 3,
|
|
"runtime_cooldown_sec": 30,
|
|
},
|
|
"telemetry_interval_sec": 10,
|
|
"theme": "dark-glass",
|
|
"lan_debug_enabled": False,
|
|
"auth_token": "",
|
|
},
|
|
)
|
|
tv_after = json.loads(ws_tv.receive_text())
|
|
tab_after = json.loads(ws_tab.receive_text())
|
|
assert tv_after["payload"]["repair_ai"]["model"] == "qwen2.5-coder:7b"
|
|
assert tab_after["payload"]["repair_ai"]["model"] == "gpt-4o-mini"
|
|
|
|
# 4. Save dedicated Hub Chat AI config & test multi-step MCP tool calling with mocked OpenAI API
|
|
r_chat_cfg = client.put(
|
|
"/api/admin/chat-ai-config",
|
|
json={
|
|
"base_url": "https://mock-openai.local/v1",
|
|
"api_key": "sk-hub-chat",
|
|
"model": "gpt-4o",
|
|
"timeout_sec": 30,
|
|
"system_prompt": "Test system prompt",
|
|
},
|
|
)
|
|
assert r_chat_cfg.status_code == 200
|
|
assert r_chat_cfg.json()["hub_chat_ai"]["max_tool_steps"] == 30
|
|
|
|
r_chat_cfg2 = client.put(
|
|
"/api/admin/chat-ai-config",
|
|
json={
|
|
"base_url": "https://mock-openai.local/v1",
|
|
"api_key": "sk-hub-chat",
|
|
"model": "gpt-4o",
|
|
"timeout_sec": 30,
|
|
"max_tool_steps": 45,
|
|
"system_prompt": "Test system prompt",
|
|
},
|
|
)
|
|
assert r_chat_cfg2.status_code == 200
|
|
assert r_chat_cfg2.json()["hub_chat_ai"]["max_tool_steps"] == 45
|
|
|
|
call_idx = {"n": 0}
|
|
|
|
def mock_handler(request: httpx.Request) -> httpx.Response:
|
|
call_idx["n"] += 1
|
|
body = json.loads(request.content.decode("utf-8"))
|
|
if call_idx["n"] == 1:
|
|
assert any(t["function"]["name"] == "list_devices" for t in body["tools"])
|
|
return httpx.Response(
|
|
200,
|
|
json={
|
|
"choices": [
|
|
{
|
|
"message": {
|
|
"role": "assistant",
|
|
"content": "",
|
|
"tool_calls": [
|
|
{
|
|
"id": "call_1",
|
|
"type": "function",
|
|
"function": {"name": "list_devices", "arguments": "{}"},
|
|
}
|
|
],
|
|
}
|
|
}
|
|
]
|
|
},
|
|
)
|
|
# Second call must include the real MCP tool output containing tv-box & tablet
|
|
tool_msgs = [m for m in body["messages"] if m.get("role") == "tool"]
|
|
assert len(tool_msgs) == 1
|
|
assert "tv-box" in tool_msgs[0]["content"]
|
|
assert "tablet" in tool_msgs[0]["content"]
|
|
return httpx.Response(
|
|
200,
|
|
json={"choices": [{"message": {"role": "assistant", "content": "已查到 2 台在线设备:客厅机顶盒与桌面平板。"}}]},
|
|
)
|
|
|
|
agent = HubMcpChatAgent(app.state.db, app.state.mcp_server, transport=httpx.MockTransport(mock_handler))
|
|
chat_res = asyncio.run(agent.chat("查询所有在线设备"))
|
|
assert chat_res["ok"] is True
|
|
assert "客厅机顶盒" in chat_res["reply"]
|
|
assert len(chat_res["tool_trace"]) == 1
|
|
assert chat_res["tool_trace"][0]["name"] == "list_devices"
|
|
assert chat_res["tool_trace"][0]["is_error"] is False
|
|
|
|
|
|
def test_persistent_multi_session_background_run_and_prompt_groups(tmp_path: Path) -> None:
|
|
import httpx
|
|
from app.admin.chat_agent import HubMcpChatAgent
|
|
|
|
db_file = str(tmp_path / "sessions_prompts.db")
|
|
app = create_app(db_file)
|
|
|
|
# Inject a slightly delayed mock OpenAI transport to verify detached background execution
|
|
def delayed_mock(request: httpx.Request) -> httpx.Response:
|
|
time.sleep(0.15)
|
|
return httpx.Response(
|
|
200,
|
|
json={"choices": [{"message": {"role": "assistant", "content": "后台任务已完成,即使浏览器关闭也不受影响!"}}]},
|
|
)
|
|
|
|
app.state.chat_agent._transport = httpx.MockTransport(delayed_mock)
|
|
|
|
with TestClient(app) as client:
|
|
# Configure hub chat AI
|
|
client.put(
|
|
"/api/admin/chat-ai-config",
|
|
json={
|
|
"base_url": "https://mock-openai.local/v1",
|
|
"api_key": "sk-bg",
|
|
"model": "gpt-4o-mini",
|
|
"timeout_sec": 30,
|
|
"system_prompt": "bg test",
|
|
},
|
|
)
|
|
|
|
# 1. Create two separate sessions
|
|
s1 = client.post("/api/admin/chat/sessions", json={"title": "新会话"}).json()["session"]
|
|
s2 = client.post("/api/admin/chat/sessions", json={"title": "第二会话"}).json()["session"]
|
|
assert s1["session_id"] != s2["session_id"]
|
|
|
|
# 2. Send message in session 1 -> returns immediately while running in background
|
|
send_res = client.post(
|
|
f"/api/admin/chat/sessions/{s1['session_id']}/messages",
|
|
json={"message": "测试关闭浏览器不中断后台任务"},
|
|
)
|
|
assert send_res.status_code == 200
|
|
data = send_res.json()
|
|
assert data["ok"] is True
|
|
assert data["assistant_message"]["status"] == "running"
|
|
# Auto-titled from first message
|
|
assert "测试关闭浏览器" in data["session"]["title"]
|
|
|
|
# 3. Poll until background task completes (simulating reopening browser later)
|
|
final_msgs = []
|
|
for _ in range(30):
|
|
mres = client.get(f"/api/admin/chat/sessions/{s1['session_id']}/messages").json()
|
|
final_msgs = mres["messages"]
|
|
if mres["session"]["status"] == "idle":
|
|
break
|
|
time.sleep(0.05)
|
|
|
|
assert len(final_msgs) == 2
|
|
assert final_msgs[0]["role"] == "user"
|
|
assert final_msgs[1]["role"] == "assistant"
|
|
assert final_msgs[1]["status"] == "done"
|
|
assert "后台任务已完成" in final_msgs[1]["content"]
|
|
|
|
# 4. Prompt groups seeded & CRUD works cleanly
|
|
groups = client.get("/api/admin/prompts").json()["groups"]
|
|
assert len(groups) >= 2
|
|
|
|
new_grp = client.post("/api/admin/prompt-groups", json={"name": "我的压测分组", "sort_order": 5}).json()["group"]
|
|
new_prm = client.post(
|
|
"/api/admin/prompts",
|
|
json={"group_id": new_grp["group_id"], "title": "一键全检", "content": "检查全部设备", "sort_order": 1},
|
|
).json()["prompt"]
|
|
upd_prm = client.put(
|
|
f"/api/admin/prompts/{new_prm['prompt_id']}",
|
|
json={"group_id": new_grp["group_id"], "title": "一键全检v2", "content": "检查全部设备与温度", "sort_order": 2},
|
|
).json()["prompt"]
|
|
assert upd_prm["title"] == "一键全检v2"
|
|
|
|
groups_after = client.get("/api/admin/prompts").json()["groups"]
|
|
mine = next(g for g in groups_after if g["group_id"] == new_grp["group_id"])
|
|
assert len(mine["prompts"]) == 1 and mine["prompts"][0]["title"] == "一键全检v2"
|
|
|
|
assert client.delete(f"/api/admin/prompt-groups/{new_grp['group_id']}").json()["deleted"] is True
|
|
|
|
|
|
def test_telemetry_history_7d_storage_cpu_and_metrics_api(tmp_path: Path) -> None:
|
|
app = create_app(str(tmp_path / "metrics.db"))
|
|
with TestClient(app) as client:
|
|
# Default interval is 3s
|
|
assert client.get("/api/admin/config").json()["telemetry_interval_sec"] == 3
|
|
|
|
with client.websocket_connect("/ws/device/box-metrics") as ws:
|
|
init_cfg = json.loads(ws.receive_text())
|
|
assert init_cfg["payload"]["telemetry_interval_sec"] == 3
|
|
|
|
ws.send_text(json.dumps({"type": "device.hello", "payload": {"device_name": "监控盒"}}))
|
|
assert json.loads(ws.receive_text())["type"] == "config.push"
|
|
|
|
ws.send_text(
|
|
json.dumps(
|
|
{
|
|
"type": "device.telemetry",
|
|
"payload": {
|
|
"cpu_usage_pct": 23.5,
|
|
"gpu_usage_pct": 18.5,
|
|
"mem_used_mb": 1400,
|
|
"mem_total_mb": 4096,
|
|
"storage_used_mb": 12288,
|
|
"storage_total_mb": 32768,
|
|
"battery_temp_c": 34.2,
|
|
"thermal_zones": {"cpu": 46.8, "gpu": 42.1},
|
|
},
|
|
}
|
|
)
|
|
)
|
|
time.sleep(0.05)
|
|
|
|
m15 = client.get("/api/admin/devices/box-metrics/metrics?range=15m").json()
|
|
assert m15["retention_days"] == 7
|
|
assert m15["point_count"] == 1
|
|
pt = m15["points"][0]
|
|
assert pt["cpu_usage_pct"] == 23.5
|
|
assert pt["gpu_usage_pct"] == 18.5
|
|
assert pt["storage_used_mb"] == 12288
|
|
assert pt["storage_total_mb"] == 32768
|
|
assert pt["max_thermal_c"] == 46.8
|
|
|
|
m7d = client.get("/api/admin/devices/box-metrics/metrics?range=7d").json()
|
|
assert m7d["point_count"] == 1
|
|
assert m7d["points"][0]["gpu_usage_pct"] == 18.5
|
|
|
|
|
|
def test_zero_latency_fmp4_muxer_no_frame_hold_and_seamless_restart() -> None:
|
|
import io
|
|
import av
|
|
from app.adb_lan.fmp4_muxer import AnnexBAccessUnitFramer, ZeroLatencyFmp4Muxer
|
|
|
|
enc_buf = io.BytesIO()
|
|
c = av.open(enc_buf, mode="w", format="h264")
|
|
s = c.add_stream("libx264", rate=25)
|
|
s.width, s.height = 320, 180
|
|
s.options = {"profile": "baseline", "tune": "zerolatency", "preset": "ultrafast"}
|
|
raw_frames: list[bytes] = []
|
|
for _ in range(4):
|
|
f = av.VideoFrame(320, 180, "rgb24")
|
|
for p in s.encode(f):
|
|
raw_frames.append(bytes(p))
|
|
for p in s.encode(None):
|
|
raw_frames.append(bytes(p))
|
|
|
|
framer = AnnexBAccessUnitFramer()
|
|
muxer = ZeroLatencyFmp4Muxer()
|
|
muxer.update_dimensions(320, 180)
|
|
|
|
out = bytearray()
|
|
for idx, rf in enumerate(raw_frames):
|
|
aus = framer.feed(rf) + framer.flush_idle()
|
|
assert len(aus) == 1
|
|
new_init, frag = muxer.mux_access_unit(aus[0][0], aus[0][1])
|
|
if idx == 0:
|
|
assert new_init is not None
|
|
out.extend(new_init)
|
|
else:
|
|
assert new_init is None
|
|
assert frag is not None
|
|
out.extend(frag)
|
|
|
|
# Seamless restart at identical SPS/PPS must NOT re-emit init segment
|
|
framer.reset()
|
|
aus_re = framer.feed(raw_frames[0]) + framer.flush_idle()
|
|
new_init2, frag2 = muxer.mux_access_unit(aus_re[0][0], aus_re[0][1])
|
|
assert new_init2 is None
|
|
assert frag2 is not None
|
|
out.extend(frag2)
|
|
|
|
dec = av.open(io.BytesIO(bytes(out)), format="mp4")
|
|
decoded = list(dec.decode(video=0))
|
|
assert len(decoded) == len(raw_frames) + 1
|
|
assert decoded[0].width == 320 and decoded[0].height == 180
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|