#!/usr/bin/env python3"""A database switch shows two states only (294 row 2, walker293). scripts/home-preview/check-switch.py <recording.mp4> [--tolerance T] [--fills-at-most N] [--launch]Reads a recording of switches (`ui-tests-stub.sh --home-walk <udid> --walkswitches`, HOME_WALK_EVERY=1 for every database along the arc and back) at60 fps, past the springboard and the app's launch. A state is a run of framesthat stand still (ten or more alike); a switch is what lies between two states. Every frame between them must be thestate before it or the state after it, over the page area (8%..55% of thescreen's height) and the fan's cards (55%..74%) — never a blank page with acard floating over it, never a fan that is neither the old arrangement nor thenew. The caps' arc below the cards springs as it is chosen and is not readfor that; it tells a switch (the caps moved) from a fill (they did not).A fill is a database with no kept answer filling in place as its read lands— its shipped arrangement once, then its own (the ruling allows it once adatabase): it is counted, not judged frame by frame, and more fills than--fills-at-most (one per database walked) is a Home dealt again.--launch reads each of the app's launches in the recording instead (295 B,walker294): the splash — the logo on the paper — then Home whole, at full,and nothing between. A launch is a run of splash frames (an even ground withthe logo at its centre); its Home is the first state after it that is not thesplash. Every frame between the splash's last frame and Home's first must beone or the other: a bare ground (paper with no logo) fails, and so does ablend of the two (a faded Home, a logo fading over it). Then Home must standas it first stood for SETTLE seconds over the page and the fan's cards — afan dealt again, a card blinking out or a page drawn a second time fails. Arecording with no launch in it fails.Needs ffmpeg and numpy. Exits 1 when a frame is neither, printing it."""import argparseimport subprocessimport sysimport numpy as npW, H = 98, 212REGIONS = [(0.08, 0.55), (0.55, 0.74)]CAPS = (0.80, 0.87, 0.25, 0.75) # the caps' row under the chosen card: top, bottom, left, rightSTILL = 0.3# mean change below which two frames are alikeRUN = 10# frames alike in a row that make a stateLAUNCH = 240# a state this bright is the white launch screen, not a HomeGROUND = 6# a frame this even below the status bar is a bare ground, whatever its colourLOGO = (0.36, 0.64, 0.30, 0.70) # where the splash's logo stands: top, bottom, left, rightSETTLE = 2.5# seconds Home must stand as it first stooddef frames(path): raw = subprocess.run( ["ffmpeg", "-v", "error", "-i", path, "-vf", f"fps=60,scale={W}:{H},format=gray", "-f", "rawvideo", "-"], capture_output=True, check=True).stdoutreturn np.frombuffer(raw, np.uint8).reshape(-1, H, W).astype(np.int16)def read(frame):return np.concatenate([frame[int(top * H):int(bottom * H)].ravel() for top, bottom in REGIONS])def distance(a, b):return float(np.abs(a - b).mean())def states(read_frames):"""Each run of RUN or more frames alike, as (first, last) indices.""" runs, start = [], 0for i in range(1, len(read_frames) + 1):if i == len(read_frames) or distance(read_frames[i], read_frames[i - 1]) >= STILL:if i - start >= RUN: runs.append((start, i - 1)) start = ireturn runsdef ground(frame):"""A bare ground: the screen below the status bar even, nothing on it."""return frame[int(0.08 * H):int(0.95 * H)].std() < GROUNDdef splash(frame):"""The splash: an even ground with the logo at its centre and nothing else.""" top, bottom, left, right = (int(LOGO[0] * H), int(LOGO[1] * H), int(LOGO[2] * W), int(LOGO[3] * W)) body = frame[int(0.08 * H):int(0.95 * H)].copy() logo = frame[top:bottom, left:right] mask = np.ones(frame.shape, bool) mask[top:bottom, left:right] = False mask[:int(0.08 * H)] = False mask[int(0.95 * H):] = False outside = frame[mask]return body.mean() <= LAUNCH and outside.std() < GROUND and logo.std() >= GROUNDdef launches(every):"""Each run of splash frames, as (first, last) indices.""" out, start = [], Nonefor i, frame in enumerate(every):if splash(frame):if start isNone: start = ielif start isnotNone: out.append((start, i - 1)) start = Noneif start isnotNone: out.append((start, len(every) - 1))# A logo-like frame or two inside Home is no launch.return [(a, b) for a, b in out if b - a + 1 >= RUN]def check_launches(every, read_frames, tolerance): runs = states(read_frames) found = launches(every) broken = 0ifnot found: print("no launch: no splash (the logo on the paper) in the recording")return1for n, (first, last) in enumerate(found): following = found[n + 1][0] if n + 1 < len(found) else len(every) home = next(((a, b) for a, b in runs if a > last and a < followingandnot splash(every[a]) andnot ground(every[a]) and every[a].mean() <= LAUNCH), None) print(f"launch {n + 1}: splash {first / 60:.3f}–{last / 60:.3f} s ({(last - first + 1) / 60:.3f} s)")if home isNone: print(f" no Home stood after the splash") broken += 1continue start = home[0] before, after = read_frames[last], read_frames[start] bad = 0for i in range(last + 1, start): near = min(distance(read_frames[i], before), distance(read_frames[i], after))if ground(every[i]): bad += 1 print(f" frame {i} ({i / 60:.3f} s): bare ground between the splash and Home")elif near > tolerance: bad += 1 print(f" frame {i} ({i / 60:.3f} s): neither the splash nor Home (off by {near:.2f}) — a blend or another layout")# Home stands as it first stood: never dealt again, nothing blinking. settled = min(start + int(SETTLE * 60), following - int(1.5 * 60), len(every) - 1) moved = 0for i in range(start, settled + 1): near = distance(read_frames[i], after)if near > tolerance: moved += 1if moved <= 5: print(f" frame {i} ({i / 60:.3f} s): Home moved after it stood (off by {near:.2f})")if moved > 5: print(f" … {moved} frames moved in all") print(f" Home at {start / 60:.3f} s, {start - last - 1} frames after the splash; " f"{bad} frames between neither, {moved} frames moved within {(settled - start) / 60:.1f} s") broken += bad + moved print(f"{len(found)} launches, {broken} frames wrong")return1if broken else0def main(): parser = argparse.ArgumentParser() parser.add_argument("recording") parser.add_argument("--tolerance", type=float, default=2.0) parser.add_argument("--fills-at-most", type=int) parser.add_argument("--launch", action="store_true") args = parser.parse_args() every = frames(args.recording) read_frames = [read(frame) for frame in every]if args.launch: sys.exit(check_launches(every, read_frames, args.tolerance)) caps = [frame[int(CAPS[0] * H):int(CAPS[1] * H), int(CAPS[2] * W):int(CAPS[3] * W)] for frame in every] runs = states(read_frames) broken = 0 switches = 0 fills = 0# Past the springboard the recording opens on and the one it ends on.for (_, before_end), (after_start, _) in zip(runs[1:], runs[2:-1]): before, after = read_frames[before_end], read_frames[after_start]if distance(before, after) < args.tolerance:continue# the same state again: a cap's spring, not a switchif before.mean() > LAUNCH or after.mean() > LAUNCH or splash(every[before_end]):continue# the launch: `--launch` reads itif distance(caps[before_end], caps[after_start]) < STILL * 3: fills += 1 print(f"fill at {after_start / 60:.3f} s")continue switches += 1for i in range(before_end + 1, after_start): near = min(distance(read_frames[i], before), distance(read_frames[i], after))if near > args.tolerance: broken += 1 print(f"frame {i} ({i / 60:.3f} s): neither the state before nor after (off by {near:.2f})") print(f"{switches} switches, {broken} frames neither old nor new, {fills} fills") too_many = args.fills_at_most isnotNoneand fills > args.fills_at_mostif too_many: print(f"more fills than {args.fills_at_most}: a Home was dealt again") sys.exit(1if broken or too_many else0)if __name__ == "__main__": main()