fix(m0): get a stopped or reloaded YouTube player going again and measure the window again
On the gaming PC the player errored about 38 s into the first window with Jarvis off; the kit had no way to notice, so every later window measured a paused, empty player, and after the user reloaded the page the injected counters were gone and the snapshot script threw, ending the stage early. - The snapshot reports a lost page (counters gone, or the script could not run while the page loaded) and the player's own error screen (first line only, bracketed IDs removed) instead of throwing. - Before each window the kit presses play on a stopped player and loads the page again when that is not enough, or when the page was lost or errored. - A window the player spoilt (error, reload, pause, ad, seek, buffering, no frames) is measured again, up to 3 times in all, with the earlier attempts and the fixes kept in the row; a lower quality or frame rate is not, since a busy GPU can cause it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -74,6 +74,6 @@ LLM 단계는 8080 포트를 씁니다. 다른 프로그램이 이 포트를 쓰
|
||||
|
||||
`run_m0_game_live.bat`을 더블클릭하면 실제 게임을 켠 상태로 잽니다(`gamemode_live`). 게임을 창 모드로 켜고 플레이 화면까지 들어간 뒤 Enter를 누르고 15초 안에 게임으로 돌아가면 됩니다. 게임 중 배치 4개(전문가 2GB·0GB, 음성 인식 GPU·CPU)를 차례로 재고 10~15분 걸리며, 끝나면 알림음이 울립니다. 게임 화면이나 게임 이름은 저장하지 않고 VRAM 사용량과 속도만 적습니다. 그래픽 메모리를 많이 쓰는 게임이면 배치가 켜지지 않을 수 있는데, 그것도 결과로 적습니다.
|
||||
|
||||
`run_m0_video.bat`을 더블클릭하면 Jarvis 옆에서 보는 영상이 끊기는지 잽니다(`video_drops`). 크롬(없으면 엣지)이 새 임시 프로필로 떠서 유튜브의 Blender 영상(Big Buck Bunny, 1080p 60fps, 소리 끔)을 틉니다. 광고가 나오면 건너뛸 수 있을 때 건너뛰고 끝날 때까지 기다립니다. 영상을 틀어 둔 채로 (1) Jarvis를 끈 상태 1분, (2) LLM(평소 배치, STT 자리와 여유 1GB)과 STT를 켜 두고 쉬는 상태 1분, (3) LLM이 답하고 STT가 10명 동시 전사를 쉬지 않고 하는 상태를 GPU 95% 제한 없이 두 번, 제한을 켜고 두 번, (4) 다시 Jarvis를 끈 상태 1분을 잽니다. 각각 끊긴 프레임 수(유튜브 "전문가용 통계"의 Dropped Frames와 같은 값)와, 화면에 프레임이 50ms·100ms 넘게 안 바뀐 횟수를 셉니다. 10~15분 걸립니다. 그동안 브라우저 창을 가리거나 최소화하지 말고 PC에 손대지 않으시면 됩니다. 광고, 일시정지, 버퍼링, 건너뛰기가 끼었거나 화질이 1080p 60fps가 아니었던 구간, 제한을 켰는데 Jarvis를 실제로 멈추지 못한 구간은 기록만 하고 비교에서는 뺍니다.
|
||||
`run_m0_video.bat`을 더블클릭하면 Jarvis 옆에서 보는 영상이 끊기는지 잽니다(`video_drops`). 크롬(없으면 엣지)이 새 임시 프로필로 떠서 유튜브의 Blender 영상(Big Buck Bunny, 1080p 60fps, 소리 끔)을 틉니다. 광고가 나오면 건너뛸 수 있을 때 건너뛰고 끝날 때까지 기다립니다. 영상을 틀어 둔 채로 (1) Jarvis를 끈 상태 1분, (2) LLM(평소 배치, STT 자리와 여유 1GB)과 STT를 켜 두고 쉬는 상태 1분, (3) LLM이 답하고 STT가 10명 동시 전사를 쉬지 않고 하는 상태를 GPU 95% 제한 없이 두 번, 제한을 켜고 두 번, (4) 다시 Jarvis를 끈 상태 1분을 잽니다. 각각 끊긴 프레임 수(유튜브 "전문가용 통계"의 Dropped Frames와 같은 값)와, 화면에 프레임이 50ms·100ms 넘게 안 바뀐 횟수를 셉니다. 10~15분 걸립니다. 그동안 브라우저 창을 가리거나 최소화하지 말고 PC에 손대지 않으시면 됩니다. 광고, 일시정지, 버퍼링, 건너뛰기가 끼었거나 화질이 1080p 60fps가 아니었던 구간, 제한을 켰는데 Jarvis를 실제로 멈추지 못한 구간은 기록만 하고 비교에서는 뺍니다. 영상이 멈추거나 유튜브 오류가 뜨거나 페이지가 새로고침되면 키트가 알아서 다시 틀고(재생을 누르고, 안 되면 페이지를 다시 엽니다) 그 구간을 최대 3번까지 다시 잽니다. 직접 새로고침하지 않으셔도 됩니다. 화질이나 프레임 수가 떨어진 구간은 GPU 탓일 수 있어서 다시 재지 않습니다.
|
||||
|
||||
다 끝나고 필요 없으면 작업 폴더(`\JarvisM0`)를 통째로 지우면 됩니다. Python, 모델, Strata(엔진과 설정 포함)는 모두 그 안에 설치하도록 지정해 두었습니다.
|
||||
|
||||
@@ -18,6 +18,7 @@ from __future__ import annotations
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
@@ -43,6 +44,10 @@ SETTLE_S = 5 # after a quality change or a seek, before a window starts
|
||||
MIN_LEFT_S = 240 # a window that could reach the end starts the video again first
|
||||
GAP_MS = (50, 100) # a gap between shown frames this long is a visible hitch at 60 fps
|
||||
ROUNDS = ("busy", "busy_cap95", "busy_cap95_2", "busy_2")
|
||||
# A window spoilt by the player (an error, a reload, a pause, an ad, buffering) is measured again, at most
|
||||
# this many times in all; one spoilt by a lower quality or frame rate is not (a busy GPU can cause that).
|
||||
ATTEMPTS = 3
|
||||
REPLAY_S = 30 # pressing play on a stopped player, before the page is loaded again
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
@@ -181,15 +186,22 @@ _INSTALL = """(() => {
|
||||
return true;
|
||||
})()""" % {"g0": GAP_MS[0], "g1": GAP_MS[1]}
|
||||
|
||||
_RESET = "(() => { const m = window.__m0; m.shown = 0; m.last = null; m.maxGap = 0; m.gaps = [0, 0]; " \
|
||||
_RESET = "(() => { const m = window.__m0; if (!m) return false; m.shown = 0; m.last = null; m.maxGap = 0; m.gaps = [0, 0]; " \
|
||||
"m.waits = 0; m.pauses = 0; m.seeks = 0; m.ad = false; m.minH = m.maxH = m.v.videoHeight; return true; })()"
|
||||
|
||||
# ``lost`` when the counters are gone (the page was loaded again, or YouTube swapped the <video>);
|
||||
# ``error`` when the player shows its own error screen (only its first line is kept, without the IDs).
|
||||
_SNAPSHOT = """(() => {
|
||||
const m = window.__m0, v = m.v, p = document.getElementById('movie_player');
|
||||
const q = v.getVideoPlaybackQuality();
|
||||
const m = window.__m0, p = document.getElementById('movie_player');
|
||||
const e = p && p.querySelector('.ytp-error');
|
||||
const error = !!(e && e.offsetParent !== null);
|
||||
const reason = error ? (e.querySelector('.ytp-error-content-wrap-reason') || e).textContent : null;
|
||||
if (!m || !m.v.isConnected) return {lost: true, error, error_text: reason};
|
||||
const v = m.v, q = v.getVideoPlaybackQuality();
|
||||
return {dropped: q.droppedVideoFrames, total: q.totalVideoFrames, shown: m.shown, max_gap_ms: m.maxGap,
|
||||
gaps: m.gaps, waits: m.waits, pauses: m.pauses, seeks: m.seeks, min_height: m.minH, max_height: m.maxH,
|
||||
ad: m.ad || !!(p && p.classList.contains('ad-showing')),
|
||||
ad_now: !!(p && p.classList.contains('ad-showing')), error, error_text: reason,
|
||||
paused: v.paused, ended: v.ended, time: v.currentTime, duration: v.duration,
|
||||
width: v.videoWidth, height: v.videoHeight,
|
||||
quality: p && p.getPlaybackQuality ? p.getPlaybackQuality() : null};
|
||||
@@ -218,11 +230,14 @@ def _js(value: Any) -> str:
|
||||
class VideoPage:
|
||||
"""The watch page in the throwaway browser."""
|
||||
|
||||
def __init__(self, cdp: Cdp, proc: subprocess.Popen | None = None, profile: Path | None = None):
|
||||
self.cdp, self.proc, self.profile = cdp, proc, profile
|
||||
def __init__(self, cdp: Cdp, proc: subprocess.Popen | None = None, profile: Path | None = None,
|
||||
url: str = VIDEO_URL):
|
||||
self.cdp, self.proc, self.profile, self.url = cdp, proc, profile, url
|
||||
self.quality = QUALITY
|
||||
|
||||
def start(self, quality: str = QUALITY, timeout: float = 180) -> dict:
|
||||
"""Wait for the video to play past any ad, then ask for ``quality``. Returns what happened."""
|
||||
self.quality = quality
|
||||
out: dict = {"started": False, "ad_seen": False, "ad_skipped": False, "quality_asked": quality}
|
||||
t0 = time.monotonic()
|
||||
while time.monotonic() - t0 < timeout:
|
||||
@@ -253,19 +268,45 @@ class VideoPage:
|
||||
out.update(quality=snap.get("quality"), width=snap.get("width"), height=snap.get("height"))
|
||||
return out
|
||||
|
||||
def keep_room(self, min_left: float = MIN_LEFT_S) -> None:
|
||||
"""Start the video again when a window could run into its end (YouTube then plays the next one)."""
|
||||
def reload(self) -> dict:
|
||||
"""Load the watch page again (its counters go with it) and get the video going as at the start."""
|
||||
self.cdp.call("Page.navigate", {"url": self.url})
|
||||
time.sleep(SETTLE_S)
|
||||
return self.start(self.quality)
|
||||
|
||||
def keep_room(self, min_left: float = MIN_LEFT_S) -> list[str]:
|
||||
"""Before a window: get a stopped, broken or reloaded player going again (pressing play first,
|
||||
loading the page again if that is not enough), and start the video again when the window could
|
||||
run into its end (YouTube then plays the next one). Returns what had to be done."""
|
||||
did: list[str] = []
|
||||
snap = self.snapshot()
|
||||
if snap.get("error"):
|
||||
did.append(f"the player showed an error: {_short(snap.get('error_text'))}")
|
||||
if snap.get("lost") or snap.get("error"):
|
||||
did.append("loaded the page again")
|
||||
self.reload()
|
||||
elif snap.get("paused") or snap.get("ended") or snap.get("ad_now") or not snap.get("height"):
|
||||
did.append("pressed play")
|
||||
if not self.start(self.quality, timeout=REPLAY_S)["started"]:
|
||||
did.append("loaded the page again")
|
||||
self.reload()
|
||||
if did:
|
||||
snap = self.snapshot()
|
||||
if (snap.get("duration") or 0) - (snap.get("time") or 0) < min_left:
|
||||
self.cdp.evaluate("(() => { document.getElementById('movie_player').seekTo(5, true); return true; })()")
|
||||
time.sleep(SETTLE_S)
|
||||
self.cdp.evaluate(_INSTALL)
|
||||
return did
|
||||
|
||||
def reset(self) -> None:
|
||||
self.cdp.evaluate(_RESET)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
return self.cdp.evaluate(_SNAPSHOT) or {}
|
||||
"""The counters; ``lost`` too when the page script could not run (the page was being loaded)."""
|
||||
try:
|
||||
return self.cdp.evaluate(_SNAPSHOT) or {}
|
||||
except RuntimeError as e:
|
||||
return {"lost": True, "script_error": _short(str(e))}
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
@@ -282,6 +323,11 @@ class VideoPage:
|
||||
shutil.rmtree(self.profile, ignore_errors=True)
|
||||
|
||||
|
||||
def _short(text: Any, n: int = 120) -> str:
|
||||
"""One line of a player message, without its bracketed IDs (YouTube adds a playback ID)."""
|
||||
return re.sub(r"\s+", " ", re.sub(r"[(\[][^)\]]*[)\]]", "", str(text or ""))).strip()[:n]
|
||||
|
||||
|
||||
def find_browser() -> str | None:
|
||||
if IS_WINDOWS:
|
||||
cands = [os.path.expandvars(p) for p in (
|
||||
@@ -317,7 +363,7 @@ def open_video_page(work: Path, url: str = VIDEO_URL, extra_args: tuple[str, ...
|
||||
page = next((p for p in (pages or []) if p.get("type") == "page" and "youtube" in p.get("url", "")),
|
||||
None) if code == 200 else None
|
||||
if page:
|
||||
return VideoPage(Cdp(page["webSocketDebuggerUrl"]), proc, profile)
|
||||
return VideoPage(Cdp(page["webSocketDebuggerUrl"]), proc, profile, url)
|
||||
time.sleep(1)
|
||||
break
|
||||
if proc.poll() is not None:
|
||||
@@ -337,7 +383,16 @@ def window_stats(before: dict, after: dict, seconds: float, want: dict | None =
|
||||
any point, buffering, the end, a reload of the counters, or (with ``want``) another quality,
|
||||
height or a lower frame rate than the source's."""
|
||||
out: dict = {"seconds": round(seconds, 1)}
|
||||
if before.get("lost") or after.get("lost"):
|
||||
# The page was loaded again (by hand or by YouTube): its counters do not relate to ``before``.
|
||||
return {**out, "frames": None, "dropped": None, "gaps_over_ms": {str(g): None for g in GAP_MS},
|
||||
"valid": False, "retry": True,
|
||||
"invalid_because": ["the page was loaded again, so its counters were gone"]
|
||||
+ ([f"the player showed an error: {_short(after.get('error_text'))}"]
|
||||
if after.get("error") else [])}
|
||||
reasons = []
|
||||
if after.get("error"):
|
||||
reasons.append(f"the player showed an error: {_short(after.get('error_text'))}")
|
||||
if after.get("total", 0) < before.get("total", 0) or after.get("dropped", 0) < before.get("dropped", 0):
|
||||
reasons.append("the video's counters started again (another video was loaded)")
|
||||
for key, why in (("ad", "an ad was showing"), ("paused", "the video was paused"), ("ended", "the video ended")):
|
||||
@@ -359,6 +414,8 @@ def window_stats(before: dict, after: dict, seconds: float, want: dict | None =
|
||||
quality=after.get("quality"), height=after.get("height"))
|
||||
if total <= 0 and not reasons:
|
||||
reasons.append("the video showed no frames")
|
||||
# Everything so far comes from the player, not from the GPU: measuring again is fair.
|
||||
out["retry"] = bool(reasons)
|
||||
if want:
|
||||
got = {before.get("quality"), after.get("quality")}
|
||||
if got != {want["quality"]}:
|
||||
@@ -410,20 +467,32 @@ def cap_problems(duty: dict, pids: list[int]) -> list[str]:
|
||||
|
||||
def measure_window(page: VideoPage, work: Callable[[], dict] | None = None,
|
||||
seconds: float | None = None, want: dict | None = WANT) -> tuple[dict, dict]:
|
||||
"""The video's stats over ``work()`` (or ``seconds`` of nothing), with the GPU's use meanwhile."""
|
||||
page.keep_room()
|
||||
page.reset()
|
||||
before = page.snapshot()
|
||||
t0 = time.perf_counter()
|
||||
done: dict = {}
|
||||
with gpucap.UtilSampler() as util:
|
||||
if work:
|
||||
done = work()
|
||||
else:
|
||||
time.sleep(QUIET_S if seconds is None else seconds)
|
||||
after = page.snapshot()
|
||||
stats = window_stats(before, after, time.perf_counter() - t0, want)
|
||||
stats["gpu_util"] = util.summary()
|
||||
"""The video's stats over ``work()`` (or ``seconds`` of nothing), with the GPU's use meanwhile.
|
||||
A window the player spoilt is measured again (``work()`` too), up to ``ATTEMPTS`` in all; the
|
||||
spoilt ones are listed under ``earlier_attempts`` and what was done to the player under ``player_fixes``."""
|
||||
earlier: list[dict] = []
|
||||
fixes: list[str] = []
|
||||
while True:
|
||||
fixes += page.keep_room()
|
||||
page.reset()
|
||||
before = page.snapshot()
|
||||
t0 = time.perf_counter()
|
||||
done: dict = {}
|
||||
with gpucap.UtilSampler() as util:
|
||||
if work:
|
||||
done = work()
|
||||
else:
|
||||
time.sleep(QUIET_S if seconds is None else seconds)
|
||||
after = page.snapshot()
|
||||
stats = window_stats(before, after, time.perf_counter() - t0, want)
|
||||
stats["gpu_util"] = util.summary()
|
||||
if stats["valid"] or not stats.get("retry") or len(earlier) + 1 >= ATTEMPTS:
|
||||
break
|
||||
earlier.append({"seconds": stats["seconds"], "invalid_because": stats["invalid_because"]})
|
||||
if earlier:
|
||||
stats["earlier_attempts"] = earlier
|
||||
if fixes:
|
||||
stats["player_fixes"] = fixes
|
||||
return stats, done
|
||||
|
||||
|
||||
@@ -441,6 +510,7 @@ def measure(r: StageResult, s: "llm.Strata", preset: dict, context: int, stt_pyt
|
||||
r["video_rows"] = rows
|
||||
r["video_source"] = {"url": url, "quality_asked": quality}
|
||||
say(" 브라우저(새 임시 프로필)로 유튜브 영상을 틉니다. 끝날 때까지 PC에 손대지 말아 주세요.")
|
||||
say(" 영상이 멈추거나 오류가 떠도 키트가 알아서 다시 틀고 그 구간을 다시 잽니다. 새로고침하지 않으셔도 됩니다.")
|
||||
try:
|
||||
page = open_video_page(s.log.parent.parent)
|
||||
except Exception as e:
|
||||
@@ -473,6 +543,8 @@ def measure(r: StageResult, s: "llm.Strata", preset: dict, context: int, stt_pyt
|
||||
x["video"] = stats
|
||||
if not stats["valid"]:
|
||||
r.note(f"{x['key']}: not counted ({'; '.join(stats['invalid_because'])})")
|
||||
for a in stats.get("earlier_attempts") or []:
|
||||
r.note(f"{x['key']}: measured again after ({'; '.join(a['invalid_because'])})")
|
||||
v = stats
|
||||
say(f" {x['key']}: 끊긴 프레임 {v['dropped']}/{v['frames']}, {GAP_MS[1]}ms 넘는 멈춤 "
|
||||
f"{v['gaps_over_ms'][str(GAP_MS[1])]}번")
|
||||
|
||||
@@ -1325,13 +1325,16 @@ def test_the_comparison_adds_up_only_valid_busy_windows_on_each_side_of_the_cap(
|
||||
|
||||
|
||||
class _FakePage:
|
||||
"""The watch page: 60 frames shown per snapshot step, a few dropped; records what the stage did."""
|
||||
"""The watch page: 60 frames shown per snapshot step, a few dropped; records what the stage did.
|
||||
``breaks_at`` lists the snapshots (counted from 1) at which the page was loaded again meanwhile;
|
||||
the player then stays broken until ``keep_room`` loads it again."""
|
||||
|
||||
def __init__(self, starts=True, quality="hd1080", height=1080):
|
||||
def __init__(self, starts=True, quality="hd1080", height=1080, breaks_at=()):
|
||||
self.starts, self.quality, self.height = starts, quality, height
|
||||
self.total = self.dropped = 0
|
||||
self.events: list[str] = []
|
||||
self.closed = False
|
||||
self.breaks_at, self.snaps, self.broken, self.reloads = set(breaks_at), 0, False, 0
|
||||
|
||||
def start(self, quality="hd1080", timeout=180):
|
||||
self.events.append("video_start")
|
||||
@@ -1339,12 +1342,21 @@ class _FakePage:
|
||||
"height": self.height if self.starts else None, "ad_seen": False}
|
||||
|
||||
def keep_room(self):
|
||||
pass
|
||||
if not self.broken:
|
||||
return []
|
||||
self.broken, self.total, self.dropped = False, 0, 0
|
||||
self.reloads += 1
|
||||
return ["loaded the page again"]
|
||||
|
||||
def reset(self):
|
||||
pass
|
||||
|
||||
def snapshot(self):
|
||||
self.snaps += 1
|
||||
if self.snaps in self.breaks_at:
|
||||
self.broken = True
|
||||
if self.broken:
|
||||
return {"lost": True}
|
||||
self.total += 3600
|
||||
self.dropped += 2
|
||||
return _snap(self.total, self.dropped, quality=self.quality, height=self.height)
|
||||
@@ -1435,6 +1447,8 @@ def test_a_video_stuck_below_the_asked_quality_counts_no_window(tmp_path, monkey
|
||||
r, _, _, _ = _run_video_stage(tmp_path, monkeypatch, fake_server, _FakePage(quality="medium", height=360))
|
||||
assert r["status"] == "partial" and any("medium" in e["error"] for e in r["errors"])
|
||||
assert not any(x["video"]["valid"] for x in r["video_rows"])
|
||||
# A lower quality may come from the GPU itself, so such a window is not measured again.
|
||||
assert not any(x["video"].get("earlier_attempts") for x in r["video_rows"])
|
||||
assert r["comparison"]["no_cap"]["windows"] == 0 and r["comparison"]["cap95"]["windows"] == 0
|
||||
|
||||
|
||||
@@ -1445,3 +1459,106 @@ def test_a_cap_that_could_not_pause_jarvis_does_not_count_as_a_capped_window(tmp
|
||||
assert r["comparison"]["cap95"]["windows"] == 0 and r["comparison"]["no_cap"]["windows"] == 2
|
||||
assert r["status"] == "partial" and any("could not be paused" in e["error"] for e in r["errors"])
|
||||
assert not running["held"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("before,after,retry", [
|
||||
(_snap(1000, 5), {"lost": True}, True), # the page was loaded again
|
||||
(_snap(1000, 5), _snap(4600, 9, error=True, error_text="x"), True), # the player's error screen
|
||||
(_snap(1000, 5), _snap(640, 0, paused=True, height=0), True), # what the gaming PC reported
|
||||
(_snap(1000, 5), _snap(4600, 9, ad=True), True),
|
||||
(_snap(1000, 5), _snap(4600, 9, waits=2), True),
|
||||
(_snap(1000, 5, quality="medium", height=360), _snap(4600, 9, quality="medium", height=360), False),
|
||||
(_snap(1000, 5), _snap(2800, 9), False), # the frame rate fell
|
||||
])
|
||||
def test_only_a_window_the_player_spoilt_is_worth_measuring_again(before, after, retry):
|
||||
from m0lib import video
|
||||
w = video.window_stats(before, after, 60.0, video.WANT)
|
||||
assert not w["valid"] and w["retry"] is retry
|
||||
|
||||
|
||||
def test_a_reloaded_page_is_measured_again_and_the_stage_goes_on(tmp_path, monkeypatch, fake_server):
|
||||
from m0lib import video
|
||||
# Two snapshots a window, one more pair for the window measured again: the video alone, then the first busy one.
|
||||
page = _FakePage(breaks_at={2, 8})
|
||||
r, _, running, stt = _run_video_stage(tmp_path, monkeypatch, fake_server, page)
|
||||
assert r["status"] == "ok" and page.reloads == 2
|
||||
rows = {x["key"]: x for x in r["video_rows"]}
|
||||
assert all(x["video"]["valid"] for x in rows.values())
|
||||
for key in ("video_only", "busy"):
|
||||
assert len(rows[key]["video"]["earlier_attempts"]) == 1
|
||||
assert rows[key]["video"]["player_fixes"] == ["loaded the page again"]
|
||||
assert any(key in n and "measured again" in n for n in r["notes"])
|
||||
assert rows["busy"]["llm"]["decode_tok_s"]["n"] > 0
|
||||
assert r["comparison"]["no_cap"]["windows"] == 2 and r["comparison"]["cap95"]["windows"] == 2
|
||||
assert page.closed and running["now"] is None and stt.loaded is None and not running["held"]
|
||||
|
||||
|
||||
def test_a_player_that_keeps_breaking_is_tried_a_few_times_per_window_and_never_stops_the_stage(
|
||||
tmp_path, monkeypatch, fake_server):
|
||||
from m0lib import video
|
||||
page = _FakePage(breaks_at=set(range(2, 400, 2))) # every window's end
|
||||
r, _, running, stt = _run_video_stage(tmp_path, monkeypatch, fake_server, page)
|
||||
rows = r["video_rows"]
|
||||
assert [x["key"] for x in rows][-1] == "video_only_again"
|
||||
assert all(not x["video"]["valid"] and len(x["video"]["earlier_attempts"]) == video.ATTEMPTS - 1 for x in rows)
|
||||
assert r["comparison"]["no_cap"]["windows"] == 0 and r["comparison"]["cap95"]["windows"] == 0
|
||||
assert page.closed and running["now"] is None and stt.loaded is None and not running["held"]
|
||||
|
||||
|
||||
class _ScriptedCdp:
|
||||
"""The DevTools side of a watch page whose player is stopped or broken until it is loaded again."""
|
||||
|
||||
def __init__(self, first: dict, plays_again: bool):
|
||||
from m0lib import video
|
||||
self.v = video
|
||||
self.first, self.plays_again = first, plays_again
|
||||
self.navigated: list[str] = []
|
||||
self.pressed = 0
|
||||
|
||||
def _ok(self) -> bool:
|
||||
return bool(self.navigated) or (self.plays_again and self.pressed > 0)
|
||||
|
||||
def evaluate(self, expr):
|
||||
if expr == self.v._SNAPSHOT:
|
||||
if not self._ok():
|
||||
return dict(self.first)
|
||||
return {**_snap(1000, 0), "paused": False, "ad_now": False, "time": 30.0, "duration": 634.0}
|
||||
if expr == self.v._STEP:
|
||||
self.pressed += 1
|
||||
return {"state": "playing" if self._ok() else "starting", "levels": ["hd1080"]}
|
||||
return True
|
||||
|
||||
def call(self, method, params=None):
|
||||
if method == "Page.navigate":
|
||||
self.navigated.append(params["url"])
|
||||
return {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("first,plays_again,reloaded", [
|
||||
({"lost": True}, False, True), # loaded again by hand: counters gone
|
||||
({**_snap(640, 0), "error": True, "error_text": "문제가 발생했습니다. (재생 ID: Ab12Cd)"}, False, True),
|
||||
({**_snap(640, 0), "paused": True, "height": 0}, True, False), # play is enough
|
||||
({**_snap(640, 0), "paused": True, "height": 0}, False, True), # play is not
|
||||
])
|
||||
def test_before_a_window_a_stopped_or_broken_player_is_started_again(monkeypatch, first, plays_again, reloaded):
|
||||
from m0lib import video
|
||||
monkeypatch.setattr(video, "SETTLE_S", 0)
|
||||
monkeypatch.setattr(video, "REPLAY_S", 0.01)
|
||||
monkeypatch.setattr(video.time, "sleep", lambda s: None)
|
||||
cdp = _ScriptedCdp(first, plays_again)
|
||||
page = video.VideoPage(cdp, url="https://example.invalid/watch")
|
||||
did = page.keep_room()
|
||||
assert cdp.navigated == (["https://example.invalid/watch"] if reloaded else [])
|
||||
assert ("loaded the page again" in did) is reloaded and did
|
||||
assert not any("Ab12Cd" in d for d in did) # YouTube's playback ID is not kept
|
||||
assert not page.snapshot().get("lost")
|
||||
|
||||
|
||||
def test_a_page_script_that_fails_while_the_page_loads_reads_as_a_lost_page():
|
||||
from m0lib import video
|
||||
|
||||
class Broken:
|
||||
def evaluate(self, expr):
|
||||
raise RuntimeError("page script failed: Execution context was destroyed.")
|
||||
|
||||
assert video.VideoPage(Broken()).snapshot()["lost"] is True
|
||||
|
||||
Reference in New Issue
Block a user