codec_check.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. #!/usr/bin/env python3
  2. """编解码兼容性回归:验证三种浏览器环境都能看到事件片段。
  3. 1) 正常浏览器(有 H.264) → 直接用 clip.mp4,不触发转码
  4. 2) 无 H.264、有 VP9 的 Chromium → 自动改用 clip.webm(服务端按需转码)
  5. 3) 两种都不支持 → 明确提示,并给出下载入口
  6. 通过 CDP 覆盖 HTMLMediaElement.canPlayType 来模拟后两种环境。
  7. """
  8. import asyncio
  9. import json
  10. import subprocess
  11. import sys
  12. import time
  13. import urllib.request
  14. from pathlib import Path
  15. import websockets
  16. CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
  17. BASE = "http://127.0.0.1:8811"
  18. VIDEO = "/Users/wenhongquan/Documents/trae_projects/yolo/output_video.mp4"
  19. NO_H264 = """(() => {
  20. const orig = HTMLMediaElement.prototype.canPlayType;
  21. HTMLMediaElement.prototype.canPlayType = function (t) {
  22. if (String(t).toLowerCase().includes('mp4')) return '';
  23. return orig.call(this, t);
  24. };
  25. })();"""
  26. NO_CODEC = """(() => {
  27. HTMLMediaElement.prototype.canPlayType = function () { return ''; };
  28. })();"""
  29. def req(method, path, data=None):
  30. body = json.dumps(data).encode() if data is not None else None
  31. r = urllib.request.Request(BASE + path, data=body, method=method)
  32. if data is not None:
  33. r.add_header("Content-Type", "application/json")
  34. with urllib.request.urlopen(r, timeout=120) as x:
  35. return json.loads(x.read() or b"{}")
  36. def prep_session() -> str:
  37. """确保存在一个带事件的会话,返回其 sid(供 ?session= 深链接使用)。"""
  38. sessions = req("GET", "/api/sessions")["sessions"]
  39. for s in sessions:
  40. evs = req("GET", f"/api/sessions/{s['id']}/events")["events"]
  41. if any(e.get("clip") and not e.get("pending") for e in evs):
  42. print(f"复用已有会话 {s['id']}({len(evs)} 个事件)")
  43. return s["id"]
  44. print("没有可用事件,先跑一次识别…")
  45. b = "----codecCheck"
  46. buf = bytearray()
  47. buf += f"--{b}\r\n".encode()
  48. buf += f'Content-Disposition: form-data; name="file"; filename="{Path(VIDEO).name}"\r\n'.encode()
  49. buf += b"Content-Type: video/mp4\r\n\r\n" + Path(VIDEO).read_bytes()
  50. buf += f"\r\n--{b}--\r\n".encode()
  51. r = urllib.request.Request(BASE + "/api/upload", data=bytes(buf), method="POST")
  52. r.add_header("Content-Type", f"multipart/form-data; boundary={b}")
  53. with urllib.request.urlopen(r, timeout=300) as x:
  54. meta = json.loads(x.read())
  55. cats = [i["id"] for g in req("GET", "/api/categories")["groups"]
  56. for i in g["items"] if i["available"]]
  57. req("POST", f"/api/sessions/{meta['id']}/config",
  58. {"categories": cats, "pre_seconds": 3, "post_seconds": 3, "detect_interval": 8})
  59. req("POST", f"/api/sessions/{meta['id']}/start")
  60. for _ in range(300):
  61. time.sleep(2)
  62. st = req("GET", f"/api/sessions/{meta['id']}")
  63. evs = req("GET", f"/api/sessions/{meta['id']}/events")["events"]
  64. if any(e.get("clip") and not e.get("pending") for e in evs):
  65. print("已生成事件片段")
  66. return
  67. if st["state"] in ("finished", "stopped", "error"):
  68. break
  69. raise RuntimeError("未能生成事件片段")
  70. class Browser:
  71. def __init__(self, port: int, patch: str | None = None):
  72. self.port = port
  73. self.patch = patch
  74. self.proc = None
  75. async def __aenter__(self):
  76. self.proc = subprocess.Popen(
  77. [CHROME, "--headless=new", "--disable-gpu", "--no-sandbox",
  78. f"--remote-debugging-port={self.port}", "--window-size=1500,1000",
  79. f"--user-data-dir=/tmp/dccai-codec-{self.port}", "about:blank"],
  80. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  81. for _ in range(80):
  82. try:
  83. urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json/version", timeout=1)
  84. break
  85. except Exception:
  86. await asyncio.sleep(0.4)
  87. tabs = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json").read())
  88. page = next(t for t in tabs if t["type"] == "page")
  89. self.ws = await websockets.connect(page["webSocketDebuggerUrl"], max_size=64 << 20)
  90. self.i = 0
  91. await self.send("Page.enable")
  92. await self.send("Runtime.enable")
  93. if self.patch:
  94. await self.send("Page.addScriptToEvaluateOnNewDocument", source=self.patch)
  95. return self
  96. async def __aexit__(self, *a):
  97. try:
  98. await self.ws.close()
  99. except Exception:
  100. pass
  101. if self.proc:
  102. self.proc.terminate()
  103. async def send(self, m, **pr):
  104. self.i += 1
  105. mid = self.i
  106. await self.ws.send(json.dumps({"id": mid, "method": m, "params": pr}))
  107. while True:
  108. r = json.loads(await self.ws.recv())
  109. if r.get("id") == mid:
  110. if "error" in r:
  111. raise RuntimeError(r["error"])
  112. return r.get("result", {})
  113. async def js(self, expr, await_promise=False):
  114. r = await self.send("Runtime.evaluate", expression=expr, returnByValue=True,
  115. awaitPromise=await_promise, userGesture=True)
  116. if r.get("exceptionDetails"):
  117. return None
  118. return r.get("result", {}).get("value")
  119. async def scenario(tag, port, patch, expect_plays, expect_src, sid=""):
  120. ok = True
  121. async with Browser(port, patch) as b:
  122. await b.send("Page.navigate", url=BASE + "/?session=" + sid)
  123. await asyncio.sleep(6)
  124. chip = await b.js("document.getElementById('codecChip').textContent")
  125. media = await b.js("JSON.stringify(MEDIA)")
  126. n = await b.js("document.querySelectorAll('.event-card').length")
  127. print(f"\n【{tag}】 {chip}")
  128. print(f" MEDIA={media} 事件卡={n}")
  129. await b.js("""(()=>{const cs=[...document.querySelectorAll('.event-card')];
  130. (cs.find(c=>!c.querySelector('.pending'))||cs[0]).click();})()""")
  131. for _ in range(45):
  132. await asyncio.sleep(1)
  133. if (await b.js("document.getElementById('mClip').readyState")) >= 3:
  134. break
  135. src = await b.js("(document.getElementById('mClip').currentSrc||'').split('/').slice(-1)[0]")
  136. info = await b.js("""(()=>{const v=document.getElementById('mClip');
  137. return JSON.stringify({rs:v.readyState,dur:v.duration?+v.duration.toFixed(2):null,
  138. w:v.videoWidth,h:v.videoHeight,err:v.error?v.error.code:null});})()""")
  139. play = await b.js("""(async()=>{const v=document.getElementById('mClip');
  140. if(!v.currentSrc) return JSON.stringify({played:false,why:'no src'});
  141. try{await v.play(); await new Promise(r=>setTimeout(r,2500));
  142. return JSON.stringify({played:v.currentTime>0.5,t:+v.currentTime.toFixed(2)});}
  143. catch(e){return JSON.stringify({played:false,why:String(e)});}})()""",
  144. await_promise=True)
  145. fb = await b.js("!document.getElementById('mClipFallback').classList.contains('hidden')")
  146. snap = await b.js("document.getElementById('mSnapshot').naturalWidth")
  147. print(f" 源={src} 状态={info}")
  148. print(f" 播放={play} 兜底提示={fb} 截图宽={snap}")
  149. def chk(label, cond):
  150. nonlocal ok
  151. print((" ✅ " if cond else " ❌ ") + label)
  152. ok = ok and bool(cond)
  153. if expect_src:
  154. chk(f"使用 {expect_src}", (src or "").endswith(expect_src))
  155. if expect_plays:
  156. chk("可内嵌播放", "played\":true" in (play or ""))
  157. chk("无兜底提示", fb is False)
  158. chk("截图可加载", bool(snap and snap > 0))
  159. else:
  160. chk("给出明确兜底提示", fb is True)
  161. return ok
  162. async def scenario_failure(port, sid=""):
  163. """片段 URL 失效时,必须给出明确提示 + 可用的下载入口(而不是静默空白)。"""
  164. ok = True
  165. async with Browser(port, NO_CODEC) as b:
  166. await b.send("Page.navigate", url=BASE + "/?session=" + sid)
  167. await asyncio.sleep(6)
  168. await b.js("""(()=>{const cs=[...document.querySelectorAll('.event-card')];
  169. (cs.find(c=>!c.querySelector('.pending'))||cs[0]).click();})()""")
  170. await asyncio.sleep(2)
  171. # 模拟片段取不到
  172. await b.js("""(()=>{const v=document.getElementById('mClip');
  173. v.src='/events/__missing__/clip.mp4'; v.load();})()""")
  174. await asyncio.sleep(3)
  175. fb = await b.js("!document.getElementById('mClipFallback').classList.contains('hidden')")
  176. txt = await b.js("document.getElementById('mClipFallback').textContent")
  177. dl = await b.js("document.getElementById('mDownloadClip').getAttribute('href')")
  178. print("\n【片段加载失败的兜底】")
  179. print(f" 提示可见={fb} 文案={str(txt)[:70]}…")
  180. print(f" 下载入口={dl}")
  181. def chk(label, cond):
  182. nonlocal ok
  183. print((" ✅ " if cond else " ❌ ") + label)
  184. ok = ok and bool(cond)
  185. chk("显示兜底提示", fb is True)
  186. chk("提示里引导下载", (await b.js("I18N.t('modal.download_clip')") or "下载片段") in (txt or ""))
  187. chk("下载链接有效", bool(dl and dl.startswith("/events/")))
  188. return ok
  189. async def main():
  190. sid = prep_session()
  191. results = []
  192. results.append(await scenario("正常浏览器(H.264 ✓)", 9341, None, True, "clip.mp4", sid))
  193. results.append(await scenario("无 H.264、有 VP9", 9342, NO_H264, True, "clip.webm", sid))
  194. results.append(await scenario_failure(9343, sid))
  195. print(f"\n结果:{sum(results)}/{len(results)} 场景通过")
  196. return 0 if all(results) else 1
  197. sys.exit(asyncio.run(main()))