| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 |
- #!/usr/bin/env python3
- """编解码兼容性回归:验证三种浏览器环境都能看到事件片段。
- 1) 正常浏览器(有 H.264) → 直接用 clip.mp4,不触发转码
- 2) 无 H.264、有 VP9 的 Chromium → 自动改用 clip.webm(服务端按需转码)
- 3) 两种都不支持 → 明确提示,并给出下载入口
- 通过 CDP 覆盖 HTMLMediaElement.canPlayType 来模拟后两种环境。
- """
- import asyncio
- import json
- import subprocess
- import sys
- import time
- import urllib.request
- from pathlib import Path
- import websockets
- CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
- BASE = "http://127.0.0.1:8811"
- VIDEO = "/Users/wenhongquan/Documents/trae_projects/yolo/output_video.mp4"
- NO_H264 = """(() => {
- const orig = HTMLMediaElement.prototype.canPlayType;
- HTMLMediaElement.prototype.canPlayType = function (t) {
- if (String(t).toLowerCase().includes('mp4')) return '';
- return orig.call(this, t);
- };
- })();"""
- NO_CODEC = """(() => {
- HTMLMediaElement.prototype.canPlayType = function () { return ''; };
- })();"""
- def req(method, path, data=None):
- body = json.dumps(data).encode() if data is not None else None
- r = urllib.request.Request(BASE + path, data=body, method=method)
- if data is not None:
- r.add_header("Content-Type", "application/json")
- with urllib.request.urlopen(r, timeout=120) as x:
- return json.loads(x.read() or b"{}")
- def prep_session() -> str:
- """确保存在一个带事件的会话,返回其 sid(供 ?session= 深链接使用)。"""
- sessions = req("GET", "/api/sessions")["sessions"]
- for s in sessions:
- evs = req("GET", f"/api/sessions/{s['id']}/events")["events"]
- if any(e.get("clip") and not e.get("pending") for e in evs):
- print(f"复用已有会话 {s['id']}({len(evs)} 个事件)")
- return s["id"]
- print("没有可用事件,先跑一次识别…")
- b = "----codecCheck"
- buf = bytearray()
- buf += f"--{b}\r\n".encode()
- buf += f'Content-Disposition: form-data; name="file"; filename="{Path(VIDEO).name}"\r\n'.encode()
- buf += b"Content-Type: video/mp4\r\n\r\n" + Path(VIDEO).read_bytes()
- buf += f"\r\n--{b}--\r\n".encode()
- r = urllib.request.Request(BASE + "/api/upload", data=bytes(buf), method="POST")
- r.add_header("Content-Type", f"multipart/form-data; boundary={b}")
- with urllib.request.urlopen(r, timeout=300) as x:
- meta = json.loads(x.read())
- cats = [i["id"] for g in req("GET", "/api/categories")["groups"]
- for i in g["items"] if i["available"]]
- req("POST", f"/api/sessions/{meta['id']}/config",
- {"categories": cats, "pre_seconds": 3, "post_seconds": 3, "detect_interval": 8})
- req("POST", f"/api/sessions/{meta['id']}/start")
- for _ in range(300):
- time.sleep(2)
- st = req("GET", f"/api/sessions/{meta['id']}")
- evs = req("GET", f"/api/sessions/{meta['id']}/events")["events"]
- if any(e.get("clip") and not e.get("pending") for e in evs):
- print("已生成事件片段")
- return
- if st["state"] in ("finished", "stopped", "error"):
- break
- raise RuntimeError("未能生成事件片段")
- class Browser:
- def __init__(self, port: int, patch: str | None = None):
- self.port = port
- self.patch = patch
- self.proc = None
- async def __aenter__(self):
- self.proc = subprocess.Popen(
- [CHROME, "--headless=new", "--disable-gpu", "--no-sandbox",
- f"--remote-debugging-port={self.port}", "--window-size=1500,1000",
- f"--user-data-dir=/tmp/dccai-codec-{self.port}", "about:blank"],
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- for _ in range(80):
- try:
- urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json/version", timeout=1)
- break
- except Exception:
- await asyncio.sleep(0.4)
- tabs = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json").read())
- page = next(t for t in tabs if t["type"] == "page")
- self.ws = await websockets.connect(page["webSocketDebuggerUrl"], max_size=64 << 20)
- self.i = 0
- await self.send("Page.enable")
- await self.send("Runtime.enable")
- if self.patch:
- await self.send("Page.addScriptToEvaluateOnNewDocument", source=self.patch)
- return self
- async def __aexit__(self, *a):
- try:
- await self.ws.close()
- except Exception:
- pass
- if self.proc:
- self.proc.terminate()
- async def send(self, m, **pr):
- self.i += 1
- mid = self.i
- await self.ws.send(json.dumps({"id": mid, "method": m, "params": pr}))
- while True:
- r = json.loads(await self.ws.recv())
- if r.get("id") == mid:
- if "error" in r:
- raise RuntimeError(r["error"])
- return r.get("result", {})
- async def js(self, expr, await_promise=False):
- r = await self.send("Runtime.evaluate", expression=expr, returnByValue=True,
- awaitPromise=await_promise, userGesture=True)
- if r.get("exceptionDetails"):
- return None
- return r.get("result", {}).get("value")
- async def scenario(tag, port, patch, expect_plays, expect_src, sid=""):
- ok = True
- async with Browser(port, patch) as b:
- await b.send("Page.navigate", url=BASE + "/?session=" + sid)
- await asyncio.sleep(6)
- chip = await b.js("document.getElementById('codecChip').textContent")
- media = await b.js("JSON.stringify(MEDIA)")
- n = await b.js("document.querySelectorAll('.event-card').length")
- print(f"\n【{tag}】 {chip}")
- print(f" MEDIA={media} 事件卡={n}")
- await b.js("""(()=>{const cs=[...document.querySelectorAll('.event-card')];
- (cs.find(c=>!c.querySelector('.pending'))||cs[0]).click();})()""")
- for _ in range(45):
- await asyncio.sleep(1)
- if (await b.js("document.getElementById('mClip').readyState")) >= 3:
- break
- src = await b.js("(document.getElementById('mClip').currentSrc||'').split('/').slice(-1)[0]")
- info = await b.js("""(()=>{const v=document.getElementById('mClip');
- return JSON.stringify({rs:v.readyState,dur:v.duration?+v.duration.toFixed(2):null,
- w:v.videoWidth,h:v.videoHeight,err:v.error?v.error.code:null});})()""")
- play = await b.js("""(async()=>{const v=document.getElementById('mClip');
- if(!v.currentSrc) return JSON.stringify({played:false,why:'no src'});
- try{await v.play(); await new Promise(r=>setTimeout(r,2500));
- return JSON.stringify({played:v.currentTime>0.5,t:+v.currentTime.toFixed(2)});}
- catch(e){return JSON.stringify({played:false,why:String(e)});}})()""",
- await_promise=True)
- fb = await b.js("!document.getElementById('mClipFallback').classList.contains('hidden')")
- snap = await b.js("document.getElementById('mSnapshot').naturalWidth")
- print(f" 源={src} 状态={info}")
- print(f" 播放={play} 兜底提示={fb} 截图宽={snap}")
- def chk(label, cond):
- nonlocal ok
- print((" ✅ " if cond else " ❌ ") + label)
- ok = ok and bool(cond)
- if expect_src:
- chk(f"使用 {expect_src}", (src or "").endswith(expect_src))
- if expect_plays:
- chk("可内嵌播放", "played\":true" in (play or ""))
- chk("无兜底提示", fb is False)
- chk("截图可加载", bool(snap and snap > 0))
- else:
- chk("给出明确兜底提示", fb is True)
- return ok
- async def scenario_failure(port, sid=""):
- """片段 URL 失效时,必须给出明确提示 + 可用的下载入口(而不是静默空白)。"""
- ok = True
- async with Browser(port, NO_CODEC) as b:
- await b.send("Page.navigate", url=BASE + "/?session=" + sid)
- await asyncio.sleep(6)
- await b.js("""(()=>{const cs=[...document.querySelectorAll('.event-card')];
- (cs.find(c=>!c.querySelector('.pending'))||cs[0]).click();})()""")
- await asyncio.sleep(2)
- # 模拟片段取不到
- await b.js("""(()=>{const v=document.getElementById('mClip');
- v.src='/events/__missing__/clip.mp4'; v.load();})()""")
- await asyncio.sleep(3)
- fb = await b.js("!document.getElementById('mClipFallback').classList.contains('hidden')")
- txt = await b.js("document.getElementById('mClipFallback').textContent")
- dl = await b.js("document.getElementById('mDownloadClip').getAttribute('href')")
- print("\n【片段加载失败的兜底】")
- print(f" 提示可见={fb} 文案={str(txt)[:70]}…")
- print(f" 下载入口={dl}")
- def chk(label, cond):
- nonlocal ok
- print((" ✅ " if cond else " ❌ ") + label)
- ok = ok and bool(cond)
- chk("显示兜底提示", fb is True)
- chk("提示里引导下载", (await b.js("I18N.t('modal.download_clip')") or "下载片段") in (txt or ""))
- chk("下载链接有效", bool(dl and dl.startswith("/events/")))
- return ok
- async def main():
- sid = prep_session()
- results = []
- results.append(await scenario("正常浏览器(H.264 ✓)", 9341, None, True, "clip.mp4", sid))
- results.append(await scenario("无 H.264、有 VP9", 9342, NO_H264, True, "clip.webm", sid))
- results.append(await scenario_failure(9343, sid))
- print(f"\n结果:{sum(results)}/{len(results)} 场景通过")
- return 0 if all(results) else 1
- sys.exit(asyncio.run(main()))
|