Skip to content

Generate clean 2D game sprites & animation atlases — component-row pipeline: state rows, alpha cleanup, frame extraction, runtime atlases. Codex/Claude skill.

fix(video): an explicit --min-len/--max-len is the window on every path that sets a cut's length

Soohong Kim125b44caf391
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b06b192..58c4f26 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,12 +5,13 @@ All notable public changes to `sprite-gen` are recorded here. Versions track the
## Unreleased - A slow walk cut one step long is named, and cut again on a count; a staff that closes only on two steps is cut as one cycle
- **New record: `cycle.step_screen` on every walk and run `video-loop --anchor motion-auto` cuts.** A walk slower than its window holds (0.5 to 1.6 s, at most half the clip) is cut one step long where its legs are drawn alike: the step repeats in pixels, the loop walks on one leg, its arms jump at the wrap, and a set aligned with it plays one step where its other directions play two. Nothing said so — the two-cycle screen looks only below the cut. Now the cut is screened the other way, over the whole clip (`period.step_screen`): the lag within 3 frames of twice the cut that repeats best (`lag`, `searched`), its distance over the cut's own over the same frames (`ratio`, `pairs`), its dip under the clip's profile (`depth`), how much of a second cycle the clip holds past it (`coverage`), and the step signal's peaks over the cut (`leg_peaks`, a record only). A repeat there (`depth` at least 0.15) better than at the cut (`ratio` at most **0.85**, `period.STEP_RATIO_MAX`) is a `suspect`. **Nothing is cut on it**: a cycle on a frame count that is not whole repeats better at its double too, so only a count of the steps settles it. Images, `strip.json`, warnings and stderr are as before, byte for byte; the report's `cycle` and the printed summary gain `step_screen`. [docs/loop-repair.md](docs/loop-repair.md#the-step-screen--a-slow-walk-cut-one-step-long).
-- **New option: `video-loop --steps 1|2`** (with `--anchor motion-auto`), the count of steps in the cut it takes without it, from whoever looked at the loop. `1` cuts the walk again in the window [2L − 1, 2L + 1] — not bounded by half the clip — with the same search, the equivalent cut whose wrap the clip itself plays taken (`choice: "closure"`) and no window twice that; a clip too short to see that window repeat is cut all the same, the count standing for the repeat (`method: "counted-window-v1"`, `unseen`). `2` keeps the cut. Either way `cycle.steps` records the count (`by: "given"`, `given`, and for `1` `first_cut` and `window`), `strip.json` says `steps: 2`, and `cycle.coverage` is (n − L) / L. **New warning**: a cut two steps long whose clip holds under 0.25 of a cycle past it (`loop.COVERAGE_MIN`) — `the cut is two steps long (… frames, one cycle) and the clip holds … of a cycle past it (under 0.25): its repeat is barely seen — the seam says whether it closes; a longer take shows it repeat`. It is cut, not refused; the seam gate judges it.
-- **Output change: an explicit `--min-len`/`--max-len` window is the window.** `--anchor motion-auto` cut the caller's ceiling back to half the clip, so asking for a slow walk's cycle (`--min-len 41 --max-len 43` on 73 frames) searched [41, 36] and failed. Only the state's default window is bounded by half the clip now.
+- **New option: `video-loop --steps 1|2`** (with `--anchor motion-auto`), the count of steps in the cut it takes without it, from whoever looked at the loop. `1` cuts the walk again in the window [2L − 1, 2L + 1] — not bounded by half the clip, but held inside an explicit `--min-len`/`--max-len` (below) — with the same search, the equivalent cut whose wrap the clip itself plays taken (`choice: "closure"`) and no window twice that; a clip too short to see that window repeat is cut all the same, the count standing for the repeat (`method: "counted-window-v1"`, `unseen`). `2` keeps the cut. Either way `cycle.steps` records the count (`by: "given"`, `given`, and for `1` `first_cut` and `window`), `strip.json` says `steps: 2`, and `cycle.coverage` is (n − L) / L. **New warning**: a cut two steps long whose clip holds under 0.25 of a cycle past it (`loop.COVERAGE_MIN`) — `the cut is two steps long (… frames, one cycle) and the clip holds … of a cycle past it (under 0.25): its repeat is barely seen — the seam says whether it closes; a longer take shows it repeat`. It is cut, not refused; the seam gate judges it.
+- **Output change: an explicit `--min-len`/`--max-len` window is the window, on every path that sets a cut's length.** `--anchor motion-auto` cut the caller's ceiling back to half the clip, so asking for a slow walk's cycle (`--min-len 41 --max-len 43` on 73 frames) searched [41, 36] and failed. Only the state's default window is bounded by half the clip now. The window is worked out once (`loop.CutWindow`) and every search reads its own off it — the first search, a window two steps long, the count (`--steps 1`), the gait fallback, the one-shot failover — so none sets a bound of its own: the `--cycle auto` one-shot failover of an action state widened an explicit `--max-len` to nine tenths of the clip (a 16-frame hop asked under `--max-len 14` was cut 36 long) and the one-shot search took no `--min-len` at all; both are held to the caller's bounds now (`detect_one_shot` honours `min_len`; `run_loop` passes `ONE_SHOT_MIN_LEN` unless `--min-len` is given, so a run without one cuts as before), and a one-shot the bounds leave no room for says so (`no complete one-shot return … — in 8-14 frames, inside --min-len 8 --max-len 14`). Whatever chose the cut, `--cycle fixed` and `pinned` included, a cut outside an explicit bound fails: `the cut is … frames long (…), outside --max-len N`. **A count and a window with no length in common fail**: `--steps 1` on a 21-frame step under `--max-len 25` cut 42 frames; now `--steps 1: the cut of 21 frames from 18 is one step, so the cycle is 41-43 frames long, and --max-len 25 leaves none of that: the count and the window disagree — drop one, or give a window that holds the cycle` (exit 1, the failed report's `cycle.steps` with `counted_window`, `window: null` and `refused`). Where they share part of the window, only that part is read (`cycle.steps.window`, `counted_window` beside it). A run with no explicit bound cuts byte for byte as before.
- **Output change: once the top of the silhouette jumps at its first choice, `video-loop --anchor motion-auto` reads the held part below its top too, and may cut two steps long — one cycle.** A staff turns about the hand as the arm swings, once a cycle; one step on it is back in place at the top band moving the other way. Where the legs are drawn alike the search takes that step as the cycle: v2.35.0 chose again on the top band alone, took such a cut — the top closed — and the shaft under the hand swung back at the wrap, with no warning. Now, behind the seam pop only, the side of the body the top band sits on is read row by row on the silhouette's outer edge (`repair.held_side`, `repair.side_edges`, `repair.held_edge` on the frames the search chooses from, `loop.HeldEdge`): per row, the cut's first and last frames against the clip's frames after its last and before its first, in place and in speed, over the row's median step in the loop; the 80th percentile over the rows is the held seam, closing under **1.2** (`repair.HELD_EDGE_REFERENCE`). Among the candidates whose top does not jump, one whose held side closes is taken (the usual 15 % of the best score, then the smallest held seam). Where none closes, windows twice a candidate's length are read — two steps of a confirmed repeat, one cycle, not themselves seen repeating — and one whose held side closes and whose top does not jump is cut: `cycle.steps` is `{"count": 2, "by": "held-edge", "step_lengths": [...]}` (the candidates it is two of, each one step), `cycle.period_local` its own length, `cycle.coverage` recorded, and `strip.json` says `steps: 2`. A cut with fewer than two clip frames either side of it cannot be read: `skipped`, counted under `unread`, never chosen. An explicit `--max-len` stays the cut's ceiling (`two_step_capped`: `max_len`, `lengths_over`), and counted steps read nothing twice as long. `cycle.seam_pop.held_edge` records `side`, `reference`, `measured`, `unread`, `doubled`, `chosen` and `two_step` (`read`, lengths tried, `measured`, `unread`, `top_pops`, `closing`); a candidate row carries `held_edge` (`null` with `held_edge_skipped`). A first choice whose top does not jump reads nothing new. [docs/loop-repair.md](docs/loop-repair.md#the-held-side--a-staff-that-closes-at-the-top-and-swings-below-the-hand).
- **New warning: a held part that no window one or two lengths long closes.** The top band's cut stands and `jolt.warnings` and stderr gain `the held part does not close at the wrap on the <side> side of the silhouette, below its top: …x its rows' median step (over 1.2); no window one or two lengths long closes it — it swings on a beat of its own` (or, where `--max-len` kept the longer windows from being read, `no window one length long closes it, and windows two lengths long (…-… frames) are over --max-len N, so they were not read`; where the steps were counted, `no window of the counted length closes it`); a held side that could not be read is said as well. Nothing fails on it.
- **Output change: `video-cycle-align` reads a loop's steps, and stops on a loop that may be one step.** A loop whose `strip.json` says `steps: 2` returns half way at its second step: that suspect is recorded `status: "steps"` (with `steps`) and does not stop the set, and the loop is resampled to the set's length like the rest; `--cycles <loop>=2` on it takes one half out and drops `steps`. A loop whose cut's report (beside the loop, or one directory up for a `video-set` item: `align.cut_report`) has `cycle.step_screen.suspect`, and whose steps nobody counted, is a suspect too (`one_step`: `length`, `lag`, `seconds`, `ratio`, `depth`, `pairs`, `coverage`, `leg_peaks`, `why`, `report`): stopped under `--multi-cycle fail` with its name and `cut it again with sprite-gen video-loop … --steps 1`, aligned and warned about under `warn`; `--cycles <loop>=1` says it holds a whole cycle. Every loop with neither is aligned as before, its row, `strip.json` and cells byte for byte.
- **`video-set`**: an item whose cut's steps are known carries `loop.steps`, one the step screen suspects `loop.step_screen` (`lag`, `ratio`, `depth`, `coverage`), and `table.md` says so in the cycle column (`46 (2 steps)`, `21 (one step?)`); a state stopped on a loop that may be one step says `<item> may be one step (cut it again with video-loop --steps 1 if it is)`. A cut two steps long now carries `ratio` like any candidate, which the item reads.
+- **`tests/video/test_explicit_window.py`** holds one table of every path that sets a length — the first search, a window two steps long, the count, the gait fallback, the one-shot failover, a fixed cut — under an explicit `--max-len` or `--min-len`, partial windows included (a held staff read only at 47 of 47-49 frames, a count read at 41-42 of 41-43): each run cuts inside the bounds or fails, and the report shows the path ran. Before this, the count (25 → 42), the one-shot failover (14 and 30 → 36) and the fixed cut (30 → 40) were cut outside them.
- **`tests/video/test_one_step_cut.py`** draws a side walker with a 42-frame cycle, legs alike and arms shaded apart, over 73 frames: v2.35.0 cuts it at 21 and says nothing; now the cut is the same and the step screen names it (`ratio` 0.48), the same drawing on 25 and 23.5 frames is written byte for byte as with no screen (23.5 a suspect that is a cycle), `--steps 1` cuts 15/42 where the arm's wrap is 0 against 7.6 for the step, `--steps 2` keeps the cut, a 50-frame clip is cut 8/42 and warned about its coverage, `--min-len 41 --max-len 43` is the window, and the set alignment stops on the step and aligns its re-cut. **`tests/video/test_loop_prop_seam_held.py`** draws a walker whose legs come back every 24 frames with a staff turning about the hand every 48: every cut one step long whose top closes reads a held seam of 2.0 to 5.2, and the window two steps long taken reads 0 and is aligned at the set's length as one cycle. A staff swinging with the step below a pennant that sways on its own beat stays one step long; a staff whose foot swings every 37 frames is kept on the top band's cut and warned about; a walk without a staff reads nothing below its top; two loops without a staff are aligned with exactly the `strip.json` and `cycle_align` keys v2.35.0 wrote.
## v2.35.0 - A staff that swings on its own beat is not cut where it jumps
diff --git a/docs/loop-repair.md b/docs/loop-repair.md
index c1d0d63..b84d5a7 100644
--- a/docs/loop-repair.md
+++ b/docs/loop-repair.md
@@ -419,14 +419,15 @@ exactly as with no screen at all.
the cut it takes without `--steps` holds.
- **`--steps 1`**: the cut is one step, so the walk is cut again two of its lengths long. The
- window is [2L − 1, 2L + 1] for the cut's length L, as given — not bounded by half the clip — and
- searched as any window (a repeat seen in the clip, the top band and the held side read again, but
+ window is [2L − 1, 2L + 1] for the cut's length L — not bounded by half the clip, but held inside an
+ explicit `--min-len`/`--max-len` (below) — and searched as any window (a repeat seen in the clip, the top band and the held side read again, but
no window twice that); among the equivalent cuts the one whose wrap the clip itself plays is taken
(`choice: "closure"`: its last frame against the clip's frame before its first, and the step into
it, over its playback step), not the earliest. A clip too short to see a window that long repeat is
cut all the same — the count stands for the repeat — at the window whose wrap the clip plays
(`method: "counted-window-v1"`, `unseen` saying why the search found none). `cycle.steps` is
- `{"count": 2, "by": "given", "given": 1, "first_cut": {start, length}, "window": [lo, hi]}`.
+ `{"count": 2, "by": "given", "given": 1, "first_cut": {start, length}, "window": [lo, hi]}`, with
+ `counted_window` beside `window` where an explicit window left only part of [2L − 1, 2L + 1].
- **`--steps 2`**: the cut is a cycle already; it is kept, and recorded `{"count": 2, "by":
"given", "given": 2}`.
@@ -441,7 +442,17 @@ warned about.
An explicit `--min-len`/`--max-len` window is the window as given too: the half-clip bound holds
only for the state's default window. v2.35.0 cut it back, so `--min-len 41 --max-len 43` on a
-73-frame clip asked for the window [41, 36] and found no cycle.
+73-frame clip asked for the window [41, 36] and found no cycle. And it is the window on every path
+that sets a cut's length — the first search, a window two steps long (the held side), the count
+(`--steps 1`), the gait fallback, the one-shot failover — each of which reads its window off one
+place (`loop.CutWindow`) and none of which sets a bound of its own; whatever chose the cut, even
+`--cycle fixed` or `pinned`, a cut outside an explicit bound fails (`CutWindow.hold`, `the cut is …
+frames long (…), outside --max-len N`). A count and a window that leave no length in common are two
+instructions that disagree, and neither is followed: `--steps 1` on a 21-frame step with
+`--max-len 25` fails with `the cut of 21 frames from 18 is one step, so the cycle is 41-43 frames
+long, and --max-len 25 leaves none of that: the count and the window disagree — drop one, or give a
+window that holds the cycle` (the failed report's `cycle.steps`: `counted_window`, `window: null`,
+`refused`). Where they share part of it, that part is read (`--max-len 42`: [41, 42]).
- **What it does not see**: a walk whose arms are drawn alike as well — then a step is a cycle in
every pixel and `ratio` reads 1; a cut whose twice is past the clip; and a cut on any path but
diff --git a/docs/loop-review.md b/docs/loop-review.md
index e14f0d1..2c9e219 100644
--- a/docs/loop-review.md
+++ b/docs/loop-review.md
@@ -100,7 +100,9 @@ nothing more is measured. Once it pops, the held part is read below its top as w
the top band sits on: a cut whose shaft closes under the hand is taken first, and where no cut one
step long closes it, a window two steps long — one cycle — is (`cycle.steps`, `strip.json`
`steps: 2`; [loop repair](loop-repair.md) section 3, "The held side"). An explicit `--max-len` is
-never widened, nor cut back to half the clip: an explicit window is the window. Without one, only
+never widened, nor cut back to half the clip: an explicit window is the window, on every path that
+sets a length (the count of steps and the one-shot failover below included), and a cut outside it
+fails ([loop repair](loop-repair.md) section 3, "The step screen"). Without one, only
the gait fallback below looks past the state's window, and only after this search found nothing.
A walk slower than the window can hold — its legs drawn alike — is found one step long, and the
diff --git a/docs/video-pipeline.md b/docs/video-pipeline.md
index ecf5283..d6f1c48 100644
--- a/docs/video-pipeline.md
+++ b/docs/video-pipeline.md
@@ -711,7 +711,9 @@ to be confirmed). The other states are fractions of the clip length: idle 60–9
(breathing is slow and not periodic — the lowest seam is a long window, and idle is
exempt from the periodicity gate), jump 11–45 %. Attack keeps the 11 % floor and
searches up to 2.5 seconds while retaining at least 0.5 seconds (and at least eight
-frames) of observed repeat context. `--min-len/--max-len` override the window.
+frames) of observed repeat context. `--min-len/--max-len` override the window — on every path that
+sets a cut's length, the gait fallback, `--steps` and the one-shot failover included; a cut outside
+them fails rather than being written.
Attack's periodicity floor is `0.15 + 0.85 * max(0, 1 - (n - lag) / lag)`:
less than a full period of comparison requires a deeper dip. Reports include both
available pairs and the every-other-frame profile sample count. This is a coverage
diff --git a/sprite_gen/video/loop.py b/sprite_gen/video/loop.py
index 6c761f4..6545ed9 100644
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@ -181,6 +181,50 @@ def profile_for(state: str | None) -> LoopProfile:
return STATE_PROFILES.get((state or "").strip().lower(), STATE_PROFILES["default"])
+@dataclass(frozen=True)
+class CutWindow:
+ """The cut's length window, worked out once (`of`) and read by every search that sets a length.
+
+ `lo`/`hi` are the first search's window: the state's, save where the caller set a bound
+ (`min_len`/`max_len`, --min-len/--max-len). A search that looks elsewhere asks this for its own
+ window — the gait fallback and the one-shot failover past the state's ceiling (`past`), a count of
+ steps two lengths on (`within`), a window two steps long (`max_len`, local_cycle's `length_cap`) —
+ and gets it inside the caller's bounds: an explicit bound is never widened, and no search sets one
+ of its own. `hold` is the last word on any cut, whatever chose it."""
+ lo: int
+ hi: int
+ min_len: int | None = None
+ max_len: int | None = None
+
+ @classmethod
+ def of(cls, prof: LoopProfile, n: int, fps: float, min_len: int | None, max_len: int | None) -> "CutWindow":
+ lo_default, hi_default = prof.window(n, fps)
+ lo = min_len if min_len is not None else lo_default
+ return cls(lo, max_len if max_len is not None else max(lo + 2, hi_default), min_len, max_len)
+
+ def within(self, lo: int, hi: int) -> tuple[int, int]:
+ """A search's own window [lo, hi] inside the caller's bounds (empty when lo > hi comes back)."""
+ return (lo if self.min_len is None else max(lo, self.min_len),
+ hi if self.max_len is None else min(hi, self.max_len))
+
+ def past(self, hi: int) -> int:
+ """The ceiling of a search past the state's window: `hi`, or the caller's own where it set one."""
+ return hi if self.max_len is None else self.max_len
+
+ def said(self) -> str:
+ """The bounds the caller set, as given on the command line."""
+ return " ".join(f"--{flag} {v}" for flag, v in (("min-len", self.min_len), ("max-len", self.max_len)) if v is not None)
+
+ def hold(self, cycle: dict[str, Any]) -> None:
+ """Raise when a cut is outside the caller's bounds: two explicit instructions that disagree are
+ a failure, never one of them followed without a word."""
+ length = cycle["length"]
+ if (self.min_len is not None and length < self.min_len) or (self.max_len is not None and length > self.max_len):
+ exc = ValueError(f"the cut is {length} frames long ({cycle.get('kind', 'cut')} from frame {cycle['start']}), outside {self.said()}")
+ exc.diagnostics = {**cycle, "window_refused": {"min_len": self.min_len, "max_len": self.max_len}} # type: ignore[attr-defined]
+ raise exc
+
+
def _load_small(path: Path) -> np.ndarray:
return _small_features(Image.open(path).convert("RGBA"))
@@ -400,13 +444,16 @@ def detect_one_shot(D: np.ndarray, *, min_len: int, max_len: int, frame_mass: np
at frame zero or n-1 is never repaired by padding. The existing contrast /
moved-mass floors still reject stand jitter; return distance must additionally
be at most a quarter of the departure. No seam threshold is relaxed.
+ No cut is shorter than `min_len` (nor ONE_SHOT_MIN_LEN) or longer than `max_len`; `run_loop`
+ passes ONE_SHOT_MIN_LEN unless the caller set --min-len (`CutWindow`).
"""
n = len(D)
adjacent = np.diag(D, 1)
candidates = []
max_moved = 0.0
+ shortest = max(ONE_SHOT_MIN_LEN, min_len)
for start in range(n - ONE_SHOT_MIN_LEN + 1):
- for end in range(start + ONE_SHOT_MIN_LEN - 1, min(n, start + max_len)):
+ for end in range(start + shortest - 1, min(n, start + max_len)):
seam = float(D[start, end])
e = (D[start] + D[end]) / 2
peak_at = start + int(np.argmax(e[start:end + 1]))
@@ -931,20 +978,32 @@ class HeldEdge:
return {"skipped": str(exc), "reference": repair_mod.HELD_EDGE_REFERENCE}
-def _counted(cycle: dict[str, Any], steps: int, *, D: np.ndarray, trajectory: np.ndarray, frames: list[Image.Image],
- moved: list[np.ndarray], detect: dict[str, Any]) -> dict[str, Any]:
+def _counted(cycle: dict[str, Any], steps: int, *, window: CutWindow, D: np.ndarray, trajectory: np.ndarray,
+ frames: list[Image.Image], moved: list[np.ndarray], detect: dict[str, Any]) -> dict[str, Any]:
"""The cut once its steps are counted (`--steps`): 2 keeps it; 1 cuts again in the window two of
- its lengths long, [2L-1, 2L+1], as long as the caller's ceiling — not half the clip — with the same
- search (a repeat seen in the clip, the top band and the held side read again) save that the cut whose
- wrap the clip itself plays is taken among the equivalent ones (`local_cycle._closure`), and no window
- twice that. A clip too short to see such a window repeat is cut all the same, the count standing
- for the repeat (`local_cycle.counted`, `unseen` says why); `cycle.coverage` and the seam gate say the
- rest. Recorded `steps` (`first_cut`: the cut counted)."""
+ its lengths long, [2L-1, 2L+1], inside the caller's bounds (`window.within`) — not half the clip —
+ with the same search (a repeat seen in the clip, the top band and the held side read again) save that
+ the cut whose wrap the clip itself plays is taken among the equivalent ones (`local_cycle._closure`),
+ and no window twice that. Where the caller's bounds leave none of [2L-1, 2L+1], the count and the
+ bounds disagree: a failure, neither followed. Where they leave part of it, that part is read
+ (`steps.window`, beside `steps.counted_window`). A clip too short to see such a window repeat is cut
+ all the same, the count standing for the repeat (`local_cycle.counted`, `unseen` says why);
+ `cycle.coverage` and the seam gate say the rest. Recorded `steps` (`first_cut`: the cut counted)."""
first = {"start": cycle["start"], "length": cycle["length"]}
if steps == 2:
cycle["steps"] = {"count": 2, "by": "given", "given": 2}
return cycle
- lo, hi = 2 * first["length"] - 1, 2 * first["length"] + 1
+ counted_window = [2 * first["length"] - 1, 2 * first["length"] + 1]
+ lo, hi = window.within(*counted_window)
+ record = {"count": 2, "by": "given", "given": 1, "first_cut": first, "window": [lo, hi]}
+ if [lo, hi] != counted_window:
+ record["counted_window"] = counted_window
+ if lo > hi:
+ exc = ValueError(f"--steps 1: the cut of {first['length']} frames from {first['start']} is one step, so the cycle is "
+ f"{counted_window[0]}-{counted_window[1]} frames long, and {window.said()} leaves none of that: the count "
+ f"and the window disagree — drop one, or give a window that holds the cycle")
+ exc.diagnostics = {**cycle, "steps": {**record, "window": None, "refused": f"outside {window.said()}"}} # type: ignore[attr-defined]
+ raise exc
signals = leg_signals(frames)
try:
found = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, length_cap=hi, signals=signals,
@@ -956,13 +1015,25 @@ def _counted(cycle: dict[str, Any], steps: int, *, D: np.ndarray, trajectory: np
except ValueError as exc:
failed = ValueError(f"--steps 1: the cut of {first['length']} frames from {first['start']} is one step, and the clip "
f"({len(D)} frames) has no window {lo}-{hi} frames long to cut: {exc}")
- failed.diagnostics = {**getattr(unseen, "diagnostics", {}), "steps": {"given": 1, "first_cut": first, "window": [lo, hi]}} # type: ignore[attr-defined]
+ failed.diagnostics = {**getattr(unseen, "diagnostics", {}), "steps": record} # type: ignore[attr-defined]
raise failed from exc
found["unseen"] = str(unseen)
- found["steps"] = {"count": 2, "by": "given", "given": 1, "first_cut": first, "window": [lo, hi]}
+ found["steps"] = record
return found
+def _one_shot(D: np.ndarray, window: CutWindow, hi: int, masses: np.ndarray) -> dict[str, Any]:
+ """`detect_one_shot` in its window: ONE_SHOT_MIN_LEN to `hi`, inside the caller's bounds. Where the
+ caller set one and no one-shot fits, the refusal says the window it searched."""
+ shortest, longest = window.within(ONE_SHOT_MIN_LEN, hi)
+ try:
+ return detect_one_shot(D, min_len=shortest, max_len=longest, frame_mass=masses)
+ except CycleSelectionError as exc:
+ if not window.said():
+ raise
+ raise CycleSelectionError(f"{exc} — in {shortest}-{longest} frames, inside {window.said()}", exc.diagnostics) from exc
+
+
def coverage_verdict(cycle: dict[str, Any]) -> list[str]:
"""A cut two steps long whose clip holds under COVERAGE_MIN of a cycle past it, in words; empty
otherwise (and for a cut whose steps are not known)."""
@@ -1030,9 +1101,9 @@ def run_loop(
raise SystemExit(f"video-loop: need at least 6 keyed frames in {frames_dir}, found {len(files)}")
prof = profile_for(state)
n = len(files)
- lo_default, hi_default = prof.window(n, fps)
- lo = min_len if min_len is not None else lo_default
- hi = max_len if max_len is not None else max(lo + 2, hi_default)
+ # Every search below reads its window off this one (`CutWindow`): none sets a bound of its own.
+ window = CutWindow.of(prof, n, fps, min_len, max_len)
+ lo, hi = window.lo, window.hi
D = distance_matrix(files)
# The clip's steps as keyed, before `--anchor motion-auto` reads its own distance or moves a frame:
# the hold is read on them, over the clip and over the cut (sprite_gen/video/held.py).
@@ -1082,7 +1153,7 @@ def run_loop(
try:
moved = moved_alpha(source_frames, analysis)
cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi, signals=leg_signals(source_frames),
- wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), length_cap=max_len, **detect)
+ wrap_pop=wrap_pop_on(moved), held_edge=HeldEdge(moved), length_cap=window.max_len, **detect)
except ValueError as first:
# A front or back gait that walked toward the camera, or a slow one: one more
# search, recorded (`gait_fallback`), and only after the first found nothing.
@@ -1097,15 +1168,15 @@ def run_loop(
report_base["automatic_motion_analysis"] = analysis
fallback["scale_undone"] = True
# An explicit --max-len is the caller's ceiling and stays one.
- hi_long = gait_fallback.long_window(lo, n, fps) if max_len is None else hi
+ hi_long = window.past(gait_fallback.long_window(lo, n, fps))
fallback["window"] = [lo, hi_long]
report_base["gait_fallback"] = fallback
try:
moved = moved_alpha(source_frames, analysis)
cycle = local_cycle.detect(D, trajectory, min_len=lo, max_len=hi_long,
- max_fraction=gait_fallback.LONG_CYCLE_FRACTION if max_len is None else .5,
+ max_fraction=gait_fallback.LONG_CYCLE_FRACTION,
signals=leg_signals(source_frames), wrap_pop=wrap_pop_on(moved),
- held_edge=HeldEdge(moved), length_cap=max_len, **detect)
+ held_edge=HeldEdge(moved), length_cap=window.max_len, **detect)
except ValueError as second:
failed = ValueError(f"{second} (also with the gait fallback: window [{lo}, {hi_long}], "
f"scale drift {drift['drift']:+.1%}{', undone' if fallback['scale_undone'] else ''})")
@@ -1114,13 +1185,13 @@ def run_loop(
failed.diagnostics = second.diagnostics # type: ignore[attr-defined]
raise failed from first
if steps is not None:
- cycle = _counted(cycle, steps, D=D, trajectory=trajectory, frames=source_frames, moved=moved, detect=detect)
+ cycle = _counted(cycle, steps, window=window, D=D, trajectory=trajectory, frames=source_frames, moved=moved, detect=detect)
elif cycle_mode == "fixed":
if start is None or length is None:
raise SystemExit("video-loop: --cycle fixed needs --start and --length")
cycle = fixed_cycle(D, start=start, length=length)
elif cycle_mode == "one-shot":
- cycle = detect_one_shot(D, min_len=lo, max_len=hi, frame_mass=masses)
+ cycle = _one_shot(D, window, hi, masses)
elif cycle_mode == "pinned":
cycle = pinned_cycle(D, seam_max=seam_max)
else:
@@ -1138,12 +1209,15 @@ def run_loop(
# explicit, recorded failover: the action happened once (allowed for this state),
# so cut rest -> excursion -> rest instead. The periodic attempt stays in the report.
periodic_attempt = {**cycle, "window": [lo, hi], "why_rejected": flat}
- cycle = detect_one_shot(D, min_len=lo, max_len=max(hi, round(n * 0.9)), frame_mass=masses)
+ # A one-shot may run past the periodic window — not past the caller's ceiling.
+ cycle = _one_shot(D, window, max(hi, round(n * 0.9)), masses)
else:
raise SystemExit(
f"video-loop: no periodic cycle found — {flat}; the motion does not repeat, widen the window, "
"regenerate the clip, or pass --cycle one-shot for a single performed action"
)
+ # Whatever chose the cut — a search, a count, --cycle fixed or pinned — it is inside the caller's bounds.
+ window.hold(cycle)
except (SystemExit, ValueError) as exc:
shutil.rmtree(out_dir.expanduser().resolve() / FALLBACK_FRAMES_DIR, ignore_errors=True)
write_loop_report(target, {**report_base, "status": "failed", "error": str(exc),
@@ -1375,8 +1449,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--out-dir", required=True, type=Path)
parser.add_argument("--fps", type=float, default=24.0, help="frame rate of the keyed frames (from the frames report)")
parser.add_argument("--state", help="motion state (idle/walk/run/jump/attack) — selects the detection window")
- parser.add_argument("--min-len", type=int, help="override: minimum cycle length in frames")
- parser.add_argument("--max-len", type=int, help="override: maximum cycle length in frames")
+ parser.add_argument("--min-len", type=int, help="override: minimum cycle length in frames, on every path that sets one (a cut shorter fails)")
+ parser.add_argument("--max-len", type=int, help="override: maximum cycle length in frames, on every path that sets one (a cut longer fails)")
parser.add_argument("--n-out", type=int, help="frames in the GIF/WebP (default: cycle seconds x --gif-fps)")
parser.add_argument("--gif-fps", type=float, default=GIF_FPS_DEFAULT, help=f"GIF/WebP playback density (default {GIF_FPS_DEFAULT:g}); every state plays at this rate regardless of cycle length")
parser.add_argument("--seam-max", type=float, default=SEAM_RATIO_MAX, help=f"loop seam gate (default {SEAM_RATIO_MAX})")
@@ -1396,7 +1470,8 @@ def add_arguments(parser: argparse.ArgumentParser) -> None:
help="--anchor motion-auto: how many steps the cut it takes without this holds, as counted by whoever looked "
"at the loop (how often each foot lands) — the report's `cycle.step_screen` names a cut that may be one "
"step. 1: the cut is one step, so the walk is cut again two of its lengths long (the window [2L-1, 2L+1], "
- "not bounded by half the clip), recorded `cycle.steps`; 2: the cut is kept, recorded. Either way the strip "
+ "not bounded by half the clip but held inside --min-len/--max-len: a window that leaves none of it "
+ "fails), recorded `cycle.steps`; 2: the cut is kept, recorded. Either way the strip "
"metadata says `steps: 2`, which `video-cycle-align` reads")
parser.add_argument("--name", default="loop", help="basename for strip/gif/webp outputs")
parser.add_argument("--report", type=Path)
diff --git a/tests/video/test_explicit_window.py b/tests/video/test_explicit_window.py
new file mode 100644
index 0000000..d20aaf6
--- /dev/null
+++ b/tests/video/test_explicit_window.py
@@ -0,0 +1,128 @@
+# SPDX-License-Identifier: Apache-2.0
+"""An explicit window (--min-len / --max-len) is the window on every path that sets a cut's length:
+the first search, a window two steps long (the held side), a count of steps (`--steps 1`), the gait
+fallback, the one-shot failover and a fixed cut. Each path asks `loop.CutWindow` for its window, and
+the cut is held to the caller's bounds (`CutWindow.hold`) whatever chose it: a cut inside them, or a
+failure — never a cut outside them (docs/loop-review.md, "An explicit --max-len is never widened").
+
+Synthetic frames only, the clips of the tests that own each path."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from sprite_gen.video import loop
+from tests.video import test_gait_fallback as fallback_clips
+from tests.video import test_loop_prop_seam_held as held_clips
+from tests.video import test_one_step_cut as step_clips
+from tests.video.test_video_pipeline import _one_shot_frames
+
+
+def _slow(root: Path) -> Path:
+ return step_clips._keyed(root) # a 42-frame cycle the walk window cuts one step (21) long
+
+
+def _short(root: Path) -> Path:
+ return step_clips._keyed(root, frames=50) # the same, too short to see a 42-frame window repeat
+
+
+def _held(root: Path) -> Path:
+ return held_clips._keyed(root) # a staff that closes below the hand only two steps (47-49) long
+
+
+def _slow_front(root: Path) -> Path:
+ keyed = root / "keyed"
+ keyed.mkdir(parents=True)
+ for k in range(73):
+ fallback_clips.walker(k, period=40).save(keyed / f"{k:03}.png") # a cycle past half the clip
+ return keyed
+
+
+def _hop(root: Path) -> Path:
+ root.mkdir(parents=True, exist_ok=True)
+ _one_shot_frames(root) # one hop, frames 60-76: no period, a one-shot
+ return root / "keyed"
+
+
+MOTION = ("--anchor", "motion-auto", "--repair", "off")
+
+# path, clip, arguments, what the report shows the path ran, and whether the cut is made at all
+ROWS = [
+ ("first", _slow, ("--state", "walk", *MOTION, "--max-len", "25"), lambda r: "gait_fallback" not in r, True),
+ ("first", _slow, ("--state", "walk", *MOTION, "--min-len", "18"), lambda r: "gait_fallback" not in r, True),
+ ("two-step", _held, ("--state", "walk", *MOTION, "--max-len", "25"),
+ lambda r: r["cycle"]["seam_pop"]["held_edge"]["two_step_capped"]["max_len"] == 25, True),
+ ("two-step", _held, ("--state", "walk", *MOTION, "--max-len", "47"), # 47 of 47-49 read
+ lambda r: r["cycle"]["seam_pop"]["held_edge"]["two_step"]["lengths"] == [47, 47]
+ and r["cycle"]["seam_pop"]["held_edge"]["two_step_capped"] == {"max_len": 47, "lengths_over": [48, 49]}, True),
+ ("two-step", _held, ("--state", "walk", *MOTION, "--min-len", "20"), lambda r: r["cycle"]["seam_pop"]["applied"], True),
+ ("counted", _slow, ("--state", "walk", *MOTION, "--max-len", "25", "--steps", "1"),
+ lambda r: r["cycle"]["steps"]["refused"] == "outside --max-len 25", False),
+ ("counted", _short, ("--state", "walk", *MOTION, "--max-len", "42", "--steps", "1"),
+ lambda r: r["cycle"]["steps"]["window"] == [41, 42] and r["cycle"]["steps"]["counted_window"] == [41, 43], True),
+ ("counted", _slow, ("--state", "walk", *MOTION, "--min-len", "18", "--steps", "1"), lambda r: r["cycle"]["steps"]["by"] == "given", True),
+ ("fallback", _slow_front, ("--state", "walk", *MOTION, "--max-len", "36"), lambda r: r["gait_fallback"]["window"] == [12, 36], False),
+ ("fallback", _slow_front, ("--state", "walk", *MOTION, "--min-len", "30"), lambda r: r["gait_fallback"]["window"][0] == 30, True),
+ ("one-shot", _hop, ("--state", "jump", "--min-len", "8", "--max-len", "14"), # the hop is 16 frames: no one-shot that short
+ lambda r: r["periodic_attempt"] is not None and r["cycle"]["kind"] == "one-shot", False),
+ ("one-shot", _hop, ("--state", "jump", "--max-len", "30"), lambda r: r["periodic_attempt"] is not None and r["cycle"]["kind"] == "one-shot", True),
+ ("one-shot", _hop, ("--state", "jump", "--min-len", "30"), lambda r: r["periodic_attempt"] is not None and r["cycle"]["kind"] == "one-shot", True),
+ ("fixed", _hop, ("--state", "jump", "--cycle", "fixed", "--start", "50", "--length", "40", "--max-len", "30"),
+ lambda r: r["cycle"]["window_refused"] == {"min_len": None, "max_len": 30}, False),
+]
+
+
+def _bound(args: tuple[str, ...], flag: str) -> int | None:
+ return int(args[args.index(flag) + 1]) if flag in args else None
+
+
[email protected]("path, clip, args, ran, cut", ROWS, ids=[f"{r[0]}{''.join(r[2][-2:])}" for r in ROWS])
+def test_an_explicit_window_holds_on_every_path(tmp_path, path, clip, args, ran, cut):
+ keyed = clip(tmp_path / "clip")
+ report_path = tmp_path / "loop.json"
+ try:
+ code = loop.main(["--frames-dir", str(keyed), "--out-dir", str(tmp_path / "out"), "--report", str(report_path), *args])
+ except SystemExit as exc:
+ code = exc.code
+ report = json.loads(report_path.read_text())
+ assert ran(report), report.get("cycle")
+ lo, hi = _bound(args, "--min-len"), _bound(args, "--max-len")
+ if not cut:
+ assert code != 0 and report["status"] == "failed", report.get("cycle")
+ return
+ assert code == 0, code
+ length = report["cycle"]["length"]
+ assert (lo is None or length >= lo) and (hi is None or length <= hi), (path, length, lo, hi)
+
+
+def test_a_count_the_window_leaves_no_room_for_fails_and_says_both(tmp_path):
+ keyed = _slow(tmp_path / "clip")
+ with pytest.raises(SystemExit) as stop:
+ loop.main(["--frames-dir", str(keyed), "--out-dir", str(tmp_path / "out"), "--state", "walk", *MOTION,
+ "--max-len", "25", "--steps", "1"])
+ said = str(stop.value)
+ assert "is one step, so the cycle is 41-43 frames long, and --max-len 25 leaves none of that" in said
+ report = json.loads((tmp_path / "out" / "loop.loop.report.json").read_text())
+ assert report["status"] == "failed" and report["error"] in said
+ assert report["cycle"]["steps"]["counted_window"] == [41, 43] and report["cycle"]["steps"]["window"] is None
+
+
+def test_a_one_shot_the_window_leaves_no_room_for_says_the_window(tmp_path):
+ keyed = _hop(tmp_path / "clip")
+ with pytest.raises(SystemExit, match=r"no complete one-shot return .* — in 8-14 frames, inside --min-len 8 --max-len 14"):
+ loop.main(["--frames-dir", str(keyed), "--out-dir", str(tmp_path / "out"), "--state", "jump", "--min-len", "8", "--max-len", "14"])
+
+
+def test_the_cut_window_is_worked_out_once():
+ walk = loop.profile_for("walk")
+ w = loop.CutWindow.of(walk, 73, 24.0, None, None)
+ assert (w.lo, w.hi, w.said()) == (12, 36, "") and w.within(41, 43) == (41, 43) and w.past(60) == 60
+ w = loop.CutWindow.of(walk, 73, 24.0, 18, 42)
+ assert (w.lo, w.hi, w.said()) == (18, 42, "--min-len 18 --max-len 42")
+ assert w.within(41, 43) == (41, 42) and w.within(83, 85) == (83, 42) and w.within(4, 90) == (18, 42) and w.past(60) == 42
+ w.hold({"start": 0, "length": 42})
+ with pytest.raises(ValueError, match="outside --min-len 18 --max-len 42"):
+ w.hold({"start": 0, "length": 43})
diff --git a/tests/video/test_gait_guard_anchor_wide.py b/tests/video/test_gait_guard_anchor_wide.py
index 4e8ddc0..78464cf 100644
--- a/tests/video/test_gait_guard_anchor_wide.py
+++ b/tests/video/test_gait_guard_anchor_wide.py
@@ -143,11 +143,14 @@ def _rest_then_short_hop(tmp_path: Path, *, n: int = 80, hop: tuple[int, int] =
def test_one_shot_accepts_a_short_excursion_below_the_periodic_window(tmp_path: Path) -> None:
files = _rest_then_short_hop(tmp_path)
D = loop_mod.distance_matrix(files)
- # 5 active frames + 2 rest each side = 9 < the periodic lower bound of 16
- cycle = loop_mod.detect_one_shot(D, min_len=16, max_len=70)
+ # 5 active frames + 2 rest each side = 9 < the periodic lower bound of 16: run_loop does not pass
+ # that bound to the one-shot search (only ONE_SHOT_MIN_LEN, or an explicit --min-len — loop.CutWindow)
+ cycle = loop_mod.detect_one_shot(D, min_len=loop_mod.ONE_SHOT_MIN_LEN, max_len=70)
assert cycle["kind"] == "one-shot"
assert cycle["length"] == 9
assert cycle["excursion"] == [40, 44]
+ # an explicit floor is the floor
+ assert loop_mod.detect_one_shot(D, min_len=16, max_len=70)["length"] >= 16
def test_feet_anchor_undoes_in_canvas_drift_and_reports_it(tmp_path: Path) -> None: