Skip to content

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

Merge origin/main (38bddef) into the loop jump repair release: the release carries main's between-cache, play modes, video-stop, logo and provider changes

Soohong Kimd3d94187395a
diff --cc CHANGELOG.md
index 4dc2a70,4fe1dd2..6950578
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -4,23 -4,30 +4,48 @@@ All notable public changes to `sprite-g
## Unreleased
+- **Fix: `video-loop --anchor motion-auto` keeps the pixel search's cut where the clip's crossings miss a pass, and where no cut of two steps closes in its place.** Seen from behind on a diagonal, the far foot passes hidden behind the near one, so the feet are seen apart once a cycle and together through the other step, its pass among them; in a clip on twos or threes a pass can also fall between two drawings. The count then sees one crossing a cycle, calls the clip's own cycle one step, and cut two cycles with `steps: 2` — which the set alignment read as settling its two-cycle screen, so the loop walked twice as fast as the rest of the set. A cut the count calls an odd number of steps has the legs swapped a cut on; where a pass can hide — the feet seen together at a pass over more than half a step, the median of the runs the clip shows whole (`crossings.Reading.overlap`, `HIDE_SHARE`) — and the clip a cut on is the same picture instead — frame by frame along the cut, its frame a cut on at most 1.0 of the cut's playback steps off (`local_cycle.same_picture`, `SAME_PICTURE_MAX`) — no legs were swapped, the count missed a crossing, and the search's cut stands, its count `uncertain` (`same-picture`, `step_count.search.same_picture`), no `steps` written. Both are asked: from the side, legs drawn alike, a step on can draw as near as the next frame, and there the feet pass briefly and the count stands. A walk whose feet stand together through most of a step and whose two steps draw nearer than a frame apart is cut one step long, as the search cut it before the count. And a search's cut the count does not refute — a two out of phase, or uncertain — whose own seam the gate passes now gives way only to a two-step cut that passed the gates (in phase, its top calm, its wrap within the seam gate of its step, its seam under the flow limit) and whose seam the gate passes; where none does, the search's cut is kept (`step_count.declined`, `step_count.search.seam`, a warning line), where before a cut whose seam the gate refuses replaced a loop it passed. A search's cut the gate refuses too, or one the count refutes — one step or three, each seen — still gives way to the two-step cut, closing or not: its wrap may yet be closed by the overlapped wrap. On the synthetic walkers the far foot hiding behind the near reads 0.03 and 0.27 playback steps a cut on (on twos and on threes), the feet together 0.60 and 0.63 of a step, and the half step drawn with a tail on its own beat 2.12; a side walker whose two steps are one silhouette, near and far a tone apart, reads 0.89 a step on — the picture alone kept its half step — and is cut two steps, its feet together briefly; a clip the search finds no cycle in and whose crossings miss a pass a cycle is still cut two cycles long ([loop-repair](docs/loop-repair.md) section 3, "The step count").
+- **Tests** — `tests/video/test_walk_steps.py` (a walker seen from behind on a diagonal, on twos and on threes, whose far foot passes hidden: the clip's one cycle, not two, no `steps`; a walker on threes whose big tail closes on no cut of two steps: the search's cut, which passes, where the two-step cut failed the seam gate; a side walker whose two steps are one silhouette, near and far a tone or four apart, cut one step by the search: two steps, its feet passing briefly, where asking the picture alone kept the half step; the half-step walker reads over the same-picture bound; on `by_steps` itself, a search's cut two steps out of phase whose own seam passes stands where every two-step cut's seam fails the gate and gives way where one passes or where its own seam fails too, a cut refuted one step gives way to a two-step cut whose seam fails, a one-step cut that is the same picture a cut on is kept where the feet stand together through a pass, and given up for two steps where they pass briefly).
+
+- **New: `video-loop --anchor motion-auto` closes a two-step cut's wrap that a part on its own beat leaves open, with the clip's frames a cycle apart.** A walk cut two steps long by the clip's crossings closes for the legs; a tail swinging round on a beat of its own closes on no cut of two steps, so the seam gate refused every one — and the eased retime does not reach it, since the part turns back at the wrap, where its frames read off the flow against the way. The clip goes on past the cut, and its frame a cycle after one of the cut's shows the legs at the same point of the walk. Under `--repair auto` (and `on`), where such a cut's wrap reads over `--seam-max` on its frames as corrected (`loop.wrap_on_cells`), the frames beside the wrap are made again before the jump repair (`repair.overlap_wrap`): each by RIFE between its two frames of one time — the clip's frame a cycle apart, moved by the analysis translation between the two and corrected as the cut frame was (`loop.cycle_apart`), and the cut's own — so the wrap plays a step the clip filmed and the part goes over to the cut's way over those frames, each frame at its own time. The weights (`repair.overlap_weights`) are the ease in and out x²(3 − 2x), held off it only in the steps where the rest of the body or a body measure, read on the line between the two frames, would go past its bound; a weight of 0 or 1 shows a frame whole, with no call, and a frame at one weight is made once, whatever the run. Four frames, then six, eight, ten and twelve (`OVERLAP_WIDTHS`), on the side — after the wrap or before it — whose frames a cycle apart differ least, never past half the loop; a run is taken only where no made frame has an interpolation fault — a part torn among them, below — the gate passes it, the loop played round still covers two steps (`loop.ring_steps`), no body measure — the foot line, the torso, the ground — moves a pixel past the largest step of the stretch as the loop plays it (the eased retime's bound on the same torso, never the clip's frames a cycle apart: the part going over pulls the body's mass, which is reported, while a torso the clip's frame a cycle on shows elsewhere would slide) — the part steps no further than over the stretch, no new rush is read, no window of the rest of the body steps further than its own largest step over the stretch, and no frame is left further off the flow over its limit (`rejected_for`). The jump repair after it makes nothing from, beside or again over those frames (`jump_repair.overlapped`). A frame made between two frames a cycle apart bridges the part's whole move at once, and where the part swings over a smaller one — a tail across a hand — RIFE drags the small part apart with it, which on art painted without a line no other reading sees: each frame is also read with RIFE's sixteen single passes (`rife.Rife.read`: the binary's eight flips and transposes, both ways in time, run one at a time with no augmentation and turned back, `rife.passes`) and refused as `torn` where the forward passes' mean and the backward passes' mean put the colour and coverage more than 0.05 apart over more than 0.21 of a window a tenth of the body high (`rife.torn`, `interpolation_quality.TORN_WARN`); the frame delivered is still the binary's own. The frames are made the weight nearest a half first, and the first frame with a fault ends its run, the rest of it not made (`unmade`), so a clip whose part crosses another on every run is refused the overlapped wrap and kept as filmed for the gate to refuse. The report carries `wrap_overlap` (each try with the weights chosen, the frames made in play order and in the order made, and the run taken; the binary's calls), the summary names it, a warning line names the frame that ended each refused run, and without RIFE the wrap is cut as filmed with a warning line (`--repair on` refuses). Each frame made costs the binary 34 calls (its frame, and its sixteen passes in colour and coverage); at most forty frames, where every width is made whole and refused. On the test walker (front, 26 frames a cycle, the tail on a 41-frame beat) the cut 29/26 reads 6.23 at the gate as filmed and 3.17 after the jump repair alone; four frames after the wrap rush the tail and are refused, six are taken, and the loop passes at 1.04, two steps, in ten calls. On a second walker whose big tuft bobs on the loop and a cycle on is carried 8 px aside a frame, the walker in its place, four frames are taken at the ease (3.41 → 1.53 at the gate, four calls): the torso moves 0.05 px, the body's mass 3.95 px against the stretch's 0.71, reported; where the whole walker also stands 3 px aside a cycle on, its torso sliding, every run is held at 0.85 of the cut's own frame next to the wrap, the wrap stays open and the cut is kept as filmed for the gate to refuse. On a third walker, painted without a line and seen from behind, whose big tail swings from 48 to −8 degrees across its hand between two frames a cycle apart, the real RIFE's frames at weights 0.5 and 0.7 read torn 0.44 and 0.26 with no other fault; swung 10 degrees past no hand, its frames read 0.04 at most ([loop-repair](docs/loop-repair.md#the-overlapped-wrap--a-part-on-its-own-beat-that-no-cut-of-two-steps-closes)).
+- **Tests** — `tests/video/test_loop_overlap.py` (a front walker whose tail swings round on its own beat, refused at the seam on every cut of two steps, is closed at the wrap: each frame beside it made between the clip's frame a cycle apart and the cut's own at its eased weight, once a frame and weight, four frames refused for a rush and six taken, two steps on the loop played round, the body within its drift, the rest of it no faster, every other frame the clip's own and nothing made by the jump repair; on a walker whose big tuft a cycle on is carried aside, every run's drift bound is the stretch's own as the loop plays it — the torso's, which stands still there, never the clip's frames a cycle apart — and the body's mass is reported beside it; with the tuft alone carried over the run is taken near the ease, the torso within its pixel while the mass moves 2 px and more past its own; with the whole walker also standing aside a cycle on, its torso sliding, no run moves it more than a pixel in a step on the frames shown, drawn again, the frame next to the wrap is held off the ease and the cut is kept as filmed; `--repair off` refused as before; without RIFE cut as filmed with a warning, and with `--repair on` refused asking for it; a made frame with a fault ends its run there — the frame nearest a half made first, the rest not made — every width refused and the cut kept as filmed; a stand-in whose passes disagree over a patch of the body ends every run at its first frame as torn, the warning naming it; the real RIFE (marked `real_rife`) drags the painted walker's hand apart between its frames a cycle apart and the frames are refused as torn, no other reading refusing them, while a swing past no hand reads nothing; a weighting search on lines drawn by hand: the ease where nothing binds, held off it in the one step a window of the rest of the body is bounded in, none where a body measure may not move); `tests/video/test_rife.py` (`Rife.read` makes the frame as every call does and then sixteen single passes with no augmentation, the pair flipped and transposed and run both ways in time: with a binary that hands back its first frame, turned back, they disagree by exactly how far the pair differs and only there; `rife.torn` reads a patch a window wide where the passes disagree and not lines a pixel or two wide, scattered pixels, a faint patch or a frame with no body).
+- **Behavior change: `video-loop --anchor motion-auto` cuts a walk two steps long — the left foot forward once and the right once — wherever the clip shows its feet pass.** Left foot forward and right foot forward are nearly the same silhouette from the side or a diagonal, so the pixel search could take one step for a cycle (a half step loop: one foot goes forward), three steps where a tail on its own beat repeated there (the wrap puts the nearer foot back: a stomp in place), or refuse a slow walk whose cycle its window could not hold. The feet are now read (`crossings.read`): where they are seen apart, each run of frames with them together is a crossing; where they never are (front, back), the foot band's lean about the body's axis changing side is, and the lean must turn over a step on. Every crossing counted is one the clip shows whole: a run cut by the clip's first or last frame counts only where its twin confirms it, every step a cut plays — on both sides of its wrap — lies within √2 of the clip's own step, and a cut is two steps only when the walk's phase advances by two over it, its wrap joins two points of a step within [1/√2 − 1, √2 − 1] of each other under every bound of what the clip does not show, and the loop as played shows two crossings too (`two`; `refuted` one or three steps; anything else `uncertain`, never two). The search's cut is kept, every image as before, where it is a two within 1.5 frames of phase; otherwise the cut is the two-step cut in phase whose top band does not pop at the wrap, whose wrap is within the seam gate of its step and whose seam is the smoothest by the flow reading (both seam frames under `repair.FLOW_LIMIT`, within 0.5 of the smoothest, the wrap nearest the clip's own way on), read on the frames moved as the cut will be corrected, of any length the count allows inside an explicit `--min-len`/`--max-len` (`method: observed-two-steps-v1`); of the first four, the first whose seam the gate will pass, read as the gate reads it (`loop.seam_on_cells`), is taken. A window that holds no two steps of a walk whose steps are seen is refused, naming both (`no cut of two steps in --max-len 25: …`), never cut one step long. A clip whose feet are not read is cut exactly as before. The report records `cycle.step_count` (the crossings, the step range, the verdict of the cut taken and of the search's cut, `chosen_by`); a cut on two steps records `cycle.steps` `{count: 2, by: crossings}` and `strip.json` `steps: 2`, so `video-cycle-align` reads its half-way return as its step, and the step screen's pixel suspicion is settled (`pixel_suspect`). Where the clip shows its steps but no cut of two, the search runs again refusing the cuts the crossings refute, and a refusal lists each window's count, those refuted last. `--steps` is still the word on the search's cut. `repair.clip_flow_states` and `repair.ring_scores` read the flow of every cut of a clip on one path; `flow_scores` and the repair read as before ([loop-repair](docs/loop-repair.md) section 3, "The step count").
+- **Tests** — `tests/video/test_crossings.py` (a walk that stalls proves no two steps across the stall, on either side of the wrap; a hold before or after the cut, a stall with the feet apart, a stand with them together, a stomp in place, the stance a clip opens on, a pass the first frame cuts with or without a twin that confirms it, a change the clip ends on: none two; half a cycle and three steps refuted, a wrap half a step off and a wrap that slips feet together in uncertain; noise at the threshold and a wobble at the axis no steps; a hold the step range absorbs stays two and a longer one does not; two crossings set no range; a lean that does not turn over is not read; every two lies in the lengths two steps cover; the lean and gap off drawn frames), `tests/video/test_walk_steps.py` (on synthetic walkers the pixel search alone cuts one step, one step past its window, three steps by the gait fallback, nothing at all, and across a stalled step: each is cut two steps long, in phase, the strip saying `steps: 2`; a walk the search already cuts two steps in phase is cut byte for byte as before; a legless body is cut as the search cuts it; a count given is the word; the set aligns a loop cut on two steps as one cycle; `detect` refuses what the crossings refute and orders a refusal by the count), the step screen's tests in `tests/video/test_one_step_cut.py` and the pixel search's in `tests/video/test_auto_motion.py`, `tests/video/test_loop_prop_seam.py` and `tests/video/test_loop_prop_seam_held.py` (a walker whose legs open and close once a drawing and never pass each other, which the count reads as one step a drawing) read their walker's feet as unseen (`tests/conftest.py`, `feet_unseen`), and `tests/video/test_explicit_window.py` refuses a `--max-len 25` that holds one step of the 42-frame walker.
+- **New: `video-loop --repair auto` (and `on`) eases a part that rushes on its way — the frames either side of the rush are made again at times that spread it, the body's own steps kept.** A part can keep its way and still jump: a tail that runs short of the cycle rushes on at the wrap, covering in one step what it covers in eight elsewhere, and each frame there lies near enough the line between its neighbours that the flow reading lets it pass, or takes the frame at the wrap out and leaves the rush over two steps. `repair.surges` reads the speed on the flow reading's own path and windows: a run of one or two steps whose mean step is at least 3.0 usual steps and 3.0 times the mean of the three steps either side, the part going on the way it came through it (a step that turns back is a frame flung, the flow repair's). After the flow groups, the worst rush is eased over three or four drawings either side, made from the frames as filmed (a frame the flow made inside is made again, `supersedes`) and kept between two frames as filmed, never leaving more than half the loop made with the rounds before it (as much as `video-loop-compare` reads back as the repair's): `repair.ease_times` gives every frame a time, on a grid of a twentieth of a step, where the part's step changes from one step to the next as little as it can — from the speed it came in with to the speed it goes on with — while the foot line's centre (`loop.foot_centre`), the torso and the lowest solid row move in a step no further than the stretch's largest step as it played and half a pixel, and every other window of the flow reading no further than its own largest step there; the torso is the head and torso the motion anchor tracks (`repair.Torso`: `auto_motion.discover` on the loop as cut, each frame matched by the anchor's masked NCC within its own fine search, 14 px across and 28 down, x to a fraction of a pixel), so a part swaying on its own beat — a tail, the hair's ends — which pulls the body's mass along and is what the repair moves, is not drift; where the anchor finds no head and torso, or one reaches the edge of that search on a frame of the loop, the body's mass (`loop.body_centre`) stands in, and the mass is reported beside the drift either way (`drift.body_mass`, `torso`); within 2 % of that, the timing nearest the frames' own. How far the part has gone is the path of its coverage's centre in the windows that read the rush, which grows as far as the part moves where a blurred distance stops growing. RIFE makes each drawing between the frames as filmed either side of its time, one call a drawing, at most nine, outside the three of the flow groups; the stretch is taken only where no frame made has an interpolation fault, no body measure moves a pixel past the stretch's largest step, the part's largest step falls, no frame is left further off the flow and over its limit, no new rush appears in the rest of the body, and no window of the rest of the body steps further on the frames made than its own largest step over the stretch as it played (`rejected_for`, `the rest faster`: the search reads the rest of the body on the line between the frames as filmed, and the frames made, which go the body's own way between them, step further where a part moves far between frames). On the synthetic walker drawn over 24 frames a cycle, the tail a quarter short goes, after the flow repair, from 5.3 usual steps into the wrap to 3.4 with no rush left; over 16 frames, 15 % short and under the flow reading's limit, from 3.6 to 1.7; over 36 frames every stretch is refused, the rest of the body 1.5 % to 19 % past its own largest step on the frames made; ordinary walks and a flung frame read no rush. A loop with no rush costs one more reading and no call. `jump_repair` carries `surge`, `surge_after`, `ease_skipped`, `ease_calls` and the round `why: ease` (its `rest`: per window the rush is not read in, `step_max_before`, `step_max_after` and `faster`), `replaced` its frames, and the summary `eased`; without RIFE the rush is cut as filmed with a warning line, and `--repair on` refuses ([loop-repair](docs/loop-repair.md) section 2, "The eased retime").
+- **Tests** — `tests/video/test_loop_ease.py` (a tail that rushes on at the wrap after the flow repair is eased over three or four drawings either side, in play order, made only from frames as filmed — the flow's frame at the wrap made again — every frame outside as it was, the part's largest step down by a quarter or more and the body's feet, torso and ground within the stretch's own steps and a pixel (the torso read as the round read it, the body's mass beside it), and every window of the rest of the body within its own largest step, read again on the loop as it plays; a rush under the flow reading's limit eased, none left; over 36 frames, the stretch whose frames made step further in the arm, the head and the legs than they did there refused for that alone, the loop as the flow left it; ordinary walks, drawn every frame and on twos, have no rush and nothing is made; a frame flung against the way is not a rush; on twos each drawing made once and shown on both its frames; a made frame pushed sideways refuses the stretch for drift, and one with its outline melted for a fault, the loop left as the flow left it; without an interpolator the rush named and nothing made; the same frames whichever way the body faces; a fourteen-frame loop eased three a side where four would leave more than half of it made; the search keeps every frame at its own time where the part moves evenly, and spreads a rush as far as the body's bound lets it; `video-loop` playing the frames made in a loop as long, a rush without RIFE cut as filmed with a warning line, `--repair on` without RIFE refused), and `tests/video/test_loop_flow.py`'s walker draws its dark parts whole on asking (`dark_whole`), so that a frame drawn between two phases has no more dark pixels than they have.
+- **Behavior change: a frame the jump repair or the cycle alignment makes between outlined drawings loses its outline only where it is lighter than its neighbours' edge rank by rank, too.** The fault `outline` read the made frame's edge against one dark line (a solid pixel under 70/255 within 2 px, `outline_loss` over 5 %), so art outlined in a mid tone — a brown or a painted line whose tone lies about 70/255 — had its line on the near side of the line in the drawings and on the far side wherever the flow softened it by a few tones: every frame made between two such drawings read as melted, and the repair and `--between auto` refused it. `rife.outline_shift(made, a, b)` reads the same edge, each pixel by how dark the darkest solid pixel within 2 px of it is, in order, against the lighter neighbour's edge at the same rank, and counts it where it is lighter by more than 50/255 (`rife.OUTLINE_SHIFT`). The fault `outline` now needs both over 5 %: a softened line is lighter by less at every rank and is kept, whatever tone the art outlines in; a line gone to the fill beside it is lighter by its whole contrast and is lost. Art outlined near-black reads the same on both, and art outlined lighter than 70/255 is still not judged by the outline. On the two-tone walker of the tests, the drawing between with its line 20 to 45 tones lighter reads `outline_loss` 57 % and `outline_shift` 0 (refused before, kept now); with its legs' line turned to fill, 24 % and 48 % (refused). A line less than 50/255 darker than the fill it melts into is not read as lost. The rank reading is read only between outlined drawings: `rife.outlined(frame)` is the share of a frame's edge whose line, the darkest solid pixel within 2 px, is darker than its fill, its colour from twice the bleed's depth inside (`rife.LINE_DEPTH`), by more than 50/255, and both neighbours must read at least 75 % (`rife.OUTLINED`); elsewhere `outline_shift` is `null` and the dark line judges alone, as before. Art painted without a line has no line to lose, and a part the flow melts there — a boot washed pale — can come out lighter by less than 50/255 at every rank: read rank by rank it would be kept and delivered, where refused it is replaced by the nearer filmed frame. On the walker of the tests painted without a line (outlined on 4 % of its edge), the drawing between with its near boot washed 40 tones lighter reads `outline_loss` 7.8 % and, rank by rank, 0: refused. The 75 % is set on frames made between drawn walks and judged by eye so that no frame seen as broken that the dark line alone refused is kept. The jump repair's proposals and the alignment's `smear` rows carry `outline_shift`, and the alignment's warning line names it where it was read; `video-loop-compare` and `video-loop-repair` keep their versioned measures, `rife.smear` alone, and judge the outline on the dark line as before ([loop-repair](docs/loop-repair.md) section 4).
+- **Tests** — `tests/video/test_outline_shift.py` (a mid-tone line drawn lighter is kept and one gone to fill is lost; the versioned measures judge on the dark line alone, and so does a measure whose rank reading was not read; art outlined near-black reads the same on both; a frame with no edge reads 0 and neighbours with none are not read; the jump repair takes a lighter line and refuses one gone to fill; the alignment keeps the one and takes the nearer frame for the other; on the walker painted without a line, a boot washed 40 tones lighter is refused by the jump repair and replaced by the alignment, and the two-tone and black walkers read outlined on all their edge; through RIFE, a short step of two-tone legs keeps its outline and legs crossing far lose it on both).
+- **Behavior change: every RIFE call runs the binary's test-time augmentation, `-x -z` (`rife.TTA`).** `-x` runs the pair as its eight flips and transposes and `-z` both ways in time, and the results are averaged, so a frame made from a to b is the one made from b to a. Neither rife-ncnn-vulkan nor Practical-RIFE has released a model since 2024; the model stays `rife-v4.6`. On the synthetic pairs of `tests/video/test_rife.py`, `-x -z` is the one setting of the four (none, `-x`, `-z`, both) that makes legs crossing far the same both ways with no ghost, and it keeps the most of a short step's outline. On the Mac's GPU it adds a tenth to half a second a frame; on Modal's CPU it costs 15 to 19 times a plain call's CPU — 12 to 30 s a 280 × 520 frame on two cores, 44 to 61 s a 960 × 960 frame. `SPRITE_GEN_RIFE_TTA` names another (`-x`, `-z`, both, or empty for none; anything else is refused before a frame is asked for), for a CPU-only machine that aligns sets. The interpolator a report names (`jump_repair.interpolator`, the alignment's `interpolator`) carries `tta`. A call past 600 s (120 s before) is stopped and reported as a RIFE that failed, where it used to end in Python's own timeout ([loop-repair](docs/loop-repair.md) section 1, "Which setting").
+- **Tests** — `tests/video/test_rife.py` (every call asks for `-x -z` and never `-g`; `SPRITE_GEN_RIFE_TTA` names either mode, both or none, and anything else is refused; a call past its time is a RIFE that failed; the real-RIFE pairs read with the augmentation: legs crossing far melt the same both ways and leave no ghost, a short step stays outlined, legs walking through each other add no dark where they cross; a refused repair names its faults whole, not by the first of a sorted list), `tests/conftest.py` (every test runs the engine's own augmentation, whatever the calling shell sets).
+- **New: the flow reading of a walk loop (`repair.flow_scores`, `repair.flow_targets`) — the frames that leave the way a part is going, by direction and speed, not by the size of a step.** Each frame is a point of the loop's path, its coverage and shading blurred by 3 % of the body height, read in nine windows of the union box: how far it lies off the straight line between its neighbours (the second difference, the acceleration), in that window's usual steps. A clip filmed on twos or threes is read on its drawings, the hold `held.measure`'s. `flow_targets` takes the worst frame at or over 3.0 first and names the fewest frames around it — one, then two — whose straight in-between brings every frame it touches under 3.0, never made from a frame taken before; what two cannot bring under is `unfixed`. On the synthetic walks an ordinary loop reads at most 1.65 where the jump score names 8 to 18 steps, and a tail flung 5 % of the body height against its sway reads 2.8 to 4.1. The methods weighed beside it — interpolation error with RIFE, optical flow, a periodic fit, a Kalman predictor, Savitzky–Golay, a Hampel test — and their sources are in docs/loop-repair.md section 2, "The flow reading".
+- **Behavior change: `video-loop --repair auto` (and `on`) takes out the frames off a walk's flow and makes them again between the frames either side, each at its own time.** The frames are the flow reading's (`repair.flow_targets`), not the jump score's: a step 1.4 times the loop's median no longer remakes the frame after it, so the quick swing of an ordinary walk is left as filmed, and a frame flung against the way a part is going, which the jump score read no larger than a swing, is taken out. A group is one or two drawings in a row; RIFE makes each drawing between the first frame of the drawing before the group and of the drawing after, at the drawing's own time (`repair.between_time`: a half for one frame, a third and two thirds for two, a half for a drawing on twos), and shows it on every frame the drawing was — the loop keeps its length, every frame its time, a loop on twos its hold. One call a drawing, at most three a loop; one made frame with an interpolation fault refuses its whole group, which keeps its frames as filmed, and nothing is made from or beside a frame made, given way or refused. Of the groups that bring the reading under the limit, `flow_targets` now takes the one whose every drawing the in-between moves furthest (`move`): two frames flung together are taken out whole, where the frame beside the pair was taken before and the pair left standing. A loop whose only large steps are the steps into and out of a few jumps no longer reads as held (`HELD_RUNS`: three in four runs must be the hold, a frame more or less): read on those false drawings its jumps read as ordinary, and a drawing made would have stood for five frames. `jump_repair` reads `reading: flow`, `limit`, `span`, `hold`, `drawings`, `refused`, `unfixed`, `left`, `off_max_before` / `off_max_after` (in place of `score_max_before` / `score_max_after`, also in the summary and in `video-set`'s item record), and per round `why: flow` with its group and `made` (per drawing: `frames`, `t`, `original`, `proposal`, `faults`, `look`); `unmade` names the group's `frames`, `neighbours` and `off`. `repair.JUMP_RATIO` is gone; `repair.jump_scores` stays, the size reading `video-loop-compare`'s jump guard reads with the recorded `facing` ([loop-repair](docs/loop-repair.md#2-jump-frames--video-loop---repair-auto)).
+- **Tests** — `tests/video/test_loop_flow.py` (an ordinary walk the jump score would remake is left alone and RIFE is not called; a flung frame made again half way between its neighbours, every other frame the video's own; two flung frames made again at a third and two thirds; on twos a flung drawing made once from the frames two before and two after it and shown on both its frames; a group with one made frame at fault keeps both frames and is not tried again; the calls go to the worst frame first and stop at three, the group left named; no interpolator names the group; mirrored, the same) and `tests/video/test_loop_repair.py` (on its block walker: one flung frame, two side by side, the pair flung at the wrap taken out whole and made from the frames beside it rather than smoothed at its edges, jumps a few frames apart read a drawing a frame and not on threes, three outline-melted groups refused within the budget, groups made only from frames as filmed; `video-loop` playing two frames made again at their own times in a loop as long, and the flow numbers when no RIFE is installed); the ghost and cross-fade proposals of `tests/video/test_ghost_screen.py`, `tests/video/test_crossfade.py` and the real-RIFE case of `tests/video/test_rife.py` read through a group the flow reading is made to name.
+- **Tests** — `tests/video/test_loop_flow.py` (an ordinary walk whose quick swing the jump score names has no frame taken; a frame flung against the sway is the one frame taken, read behind the body and turning back; a tail that snaps back at a wrap that does not close takes a frame at the wrap; the same whichever way the body faces; a walk on twos read on its drawings, a drawing flung the two frames that show it; two frames flung in a row one group of two; three flung frames three groups, none made from a frame taken before; a span too short named `unfixed`; a loop of three drawings left alone; a loop with no body refused).
++
+ - **New: `video-cycle-align --between-cache DIR` caches frames made between source frames so later alignments take kept frames instead of making them again.** Previously, running alignment a second time to specify `--foot` or after a retake remade every interpolated frame, even though source frames and fractions did not change. Now, every frame RIFE makes between two source frames is saved in `DIR` as a PNG keyed by the sha256 of its inputs and interpolator identity, and any later run with identical inputs reuses the kept frame. The interpolator identity is read for every frame, so a binary, model or host that changed makes the frame again. A frame made while its inputs changed is handed on but not kept (`not_kept`). The user passes `--between-cache DIR` (or `between_cache=path` in Python) and removes `DIR` when the alignment is done. The summary and report record `dir`, `hits`, `misses`, `unreadable`, and `not_kept` under `between_cache`, which is `null` without the flag ([loop repair](docs/loop-repair.md#4-one-cycle-for-a-direction-set--video-cycle-align-video-set---align-cycles-auto)).
+ - **Tests**: `tests/video/test_between_cache.py` (two passes under `--between rife` and `--between auto`: the second takes every kept frame, with matching files and report; one changed source pixel remakes only the frames made from it while the others are taken; another length gives the same loops as a pass without the directory; swapped frames, another fraction (even one a float apart) or one moved pixel miss; frames that are not RGBA are refused; under one `rife.Rife` object, with a stand-in RIFE that runs and picks its output by its model's and its own bytes: its model's bytes written over, its binary written over, a file added to its model, and its model files under another directory name each make the frame again, and every frame taken equals the frame the same object makes without the directory; a RIFE whose model directory is gone fails as a RIFE that fails; under one `rife.Rife`: another host name or OS build, NumPy or Pillow version, or engine code loaded anew make the frame again, while `rife.py` written over on disk after the import (no code that runs) takes the frame the loaded code made; a frame made while its model was written over between RIFE's two runs is handed on as made and not kept (`not_kept`), and the next pass makes it again; corrupt, truncated or overwritten kept files are made again and written over; the directory and its files are readable and writable by the user only (no group or other permission bits); alignments without the flag store nothing; injected interpolators without an `identity()` method are refused; the summary and report record the cache counts; a `real_rife` run matches the sha256 of fresh frames). Synthetic fixtures only.
+
+ - **Behavior change: a call that names no provider stops and asks when codex cannot run, unless you chose what to do.** `gen`, `logo`, `gen-set` and `video-set`'s mid-step redraw run on codex when no `--provider` is named. When codex was not signed in, they used to switch to `grok` without asking (said on stderr, kept in the report) — and with no Grok login that meant `XAI_API_KEY`, billed per call. Now codex that cannot run — not signed in (`codex login status`), or its usage used up (`codex exec` ends on one of the errors codex classes as its usage limit) — follows a choice: `ask` (the default) generates nothing and ends with one stderr line, `sprite-gen ask codex-unavailable: {…}` (the cause, the reason, the question and the flag that runs each answer), and **exit 75**; `grok` or `openai` runs that provider, said on stderr and kept in the report as `provider_fallback` (now with `cause` and `chosen_by`), `openai` with its per-call charge line as always. The choice is `SPRITE_GEN_CODEX_UNAVAILABLE`, else `sprite-gen defaults save --codex-unavailable ask|grok|openai`, else `ask`; the guided `workflow` asks it once and saves it. A usage limit is known only after `codex exec` ran, so the call runs again on the chosen provider. A named `--provider` runs as named: a named codex whose usage is used up still fails with codex's own words, exit 1. `gen-set` and `video-set` whose child asked stop with the same question and exit 75 (naming `--provider`, or `--still-provider`), their reports and tables keep it under `asked`, and `gen-set --provider` now takes `openai`. `openai` runs only when you chose it: named, or as this answer — still never a default, never the guided image provider ([gen](docs/gen.md#when-codex-cannot-run--ask-or-what-you-chose), [SKILL](SKILL.md#when-codex-cannot-run--exit-75)).
+ - **The usage-limit signal is codex's own words, read from its source** (codex-rs at `rust-v0.160.1` and `rust-v0.153.4`): `codex exec --json` carries only the message of codex's usage-limit errors (`UsageLimitReached`, `QuotaExceeded`, `UsageNotIncluded`, which codex classes as `UsageLimitExceeded`), so `codex_provider.usage_limit` matches the start of each message as codex's tests pin it — "You've hit your usage limit" with either apostrophe (0.153.4 writes it ASCII, 0.160.1 as U+2019), "Your workspace is out of credits.", "You hit your spend cap set", "Quota exceeded. Check your plan and billing details." and "To use Codex with your ChatGPT plan, upgrade to Plus". Any other codex failure is a failure, not the question.
+ - **Preferences file version 2.** `preferences.json` keeps, beside the `sprite` and `image` profiles, the `general` settings every profile shares (`codex_unavailable`). A version 1 file still reads, with nothing chosen; the next save writes version 2, which an earlier sprite-gen refuses as unknown. `defaults save --codex-unavailable` needs no `--kind`.
+ - **Tests** — `tests/gen/test_codex_unavailable.py` (no codex on PATH and nothing chosen: a real `gen` exits 75 with one question line and no image or report; each of codex's usage-limit sentences, synthesized as `codex exec --json` prints them, asks the same; a codex failure that is not its usage limit fails and is not switched; saved `grok` runs grok and the report and stderr say whose choice; saved `openai` runs the API on a fake transport with one charge line; a usage limit with saved `grok` runs grok after codex; the environment before the saved choice, an unknown value refused; settings read only when codex cannot run; `logo` resolves the same way; a named provider runs as named whatever was chosen; a real `gen-set` whose rows asked exits 75 with one question naming `--provider`, its report and table keeping it; a `video-set` whose mid-step redraw asked stops naming `--still-provider`; the guide asks once and not after the answer is saved, nor over the environment; the choice kept beside the profiles, a version 1 file read; the `defaults` CLI; SKILL.md names the exit code, the line and the three answers). Every test now runs on its own settings directory with no provider environment (`tests/conftest.py`).
+
+ - **Behavior change: a refused provider request is sent again only within the time limit of its call, and the waits count in that limit.** Previously a request its provider documents as not taken (a 429, an overload) was sent again after 8 s and 16 s, or after the answer's `retry-after` (at most 120 s), twice, whatever time the call had left, and the time limits did not count those waits: `SPRITE_GEN_GEN_TIMEOUT_SECONDS` bounded each send of an OpenAI or Grok image and of the OpenAI facing check on its own, the Grok facing check's 120 s each read, the clip's poll timeout counted from the send xAI accepted, and a Message Batch's status and results reads waited outside `--batch-wait`. A caller that stops the run at its own ceiling, set above those limits, could kill a request taken after two refusals and hear nothing from the engine. Now each limit counts from the first send and holds the waits: the image calls and the OpenAI facing check count `SPRITE_GEN_GEN_TIMEOUT_SECONDS`, the Grok facing check its 120 s, each of their sends reading only what is left of it; the clip its poll timeout (`SPRITE_GEN_VIDEO_TIMEOUT_SECONDS`; the POST itself is still not cut, its answer being the one way to the request id); a batch's reads `--batch-wait`. A wait that would reach the limit is not waited: the refusal ends the call as any refusal does, after one stderr line, `[gen] openai refused the request (429 rate_limit_exceeded); nothing was made — not asking again: the 16s wait would reach the time limit (12s left)`. The limit is read again after the wait, right before the send, as a sleep may wake later than it was asked to: one that woke at the limit or past it sends nothing either, and the refusal ends the call the same way (`… — not asking again: the time limit came during the 8s wait`). A clip's polls and downloads read their poll timeout the same way: a poll or download whose wait woke at it or past it is not sent, and the run ends unfinished on the last one as it came, where the one the transport found no time left to send was counted as a poll or download that got no answer (`timed out`). A realtime `pixel-draw` call has no time limit of its own and is unchanged.
+ - **Tests** — `tests/gen/test_retry.py` (a request sent again only while its wait ends before the time limit; the answer's `retry-after` counted the same; a wait that ends at the limit not waited; a wait that woke at the limit or past it sends nothing, the limit read by one judgment, `too_late`, before the wait and right before the send; every direct provider call hands `retry` its limit; the Grok facing check and a Message Batch read whose wait woke past their limit send nothing), `tests/gen/test_openai_provider.py` and `tests/gen/test_grok_provider.py` (with 20 s, the second send waits only the 12 s left and the second 429 ends the call `sent 2 times`; with 8.01 s, an 8 s wait that woke 20 ms late sends nothing and the 429 ends the image call, or the OpenAI facing check, as it came), `tests/gen/test_video.py` (the poll timeout counts from the first send; a 429 whose next wait would reach it ends the run with its status, and so does one whose 8 s wait woke 20 ms past an 8.01 s timeout, with no second POST; a poll or a download whose wait woke past the timeout is not sent, and the run ends on the last one as it came), `tests/gen/test_pixel_draw.py` (each batch read is handed the end of `--batch-wait`). `tests/http_answer.py` is one offline HTTP answer the provider tests share, read whole or a chunk at a time under a deadline.
+ - **Behavior change: requests can pack sound without images.** Previously, a version 1 request required a nonempty `assets` list (refused with "assets must be a nonempty list"), and version 2 required at least one asset, image, tile, UI kit or icon (refused with "game pack request declares nothing to pack"), preventing games drawn in code from packing audio alone. In both versions, `assets` may now be empty or absent when sound is declared (see [docs/game-pack.md#sound-only-packs](docs/game-pack.md#sound-only-packs)). A sound-only request writes exactly `game-pack.json`, `audio-<id>.ogg`, `audio-<id>.m4a` and `sprite-gen-audio-v2.mjs` without atlas pages; its manifest sets `textures` to `[]` and `animations` to `{}` (version 2 also keeps empty `images`, `tiles` and `ui`), while audio entries, sound files and helper module bytes remain identical to packs with images. Requests declaring no assets, scene entries or sounds are refused in both versions with "game pack request declares nothing to pack: give it an asset, a scene entry or a sound" and write nothing. Packs with images (with or without sound) and packs without sound remain byte-for-byte unchanged, and repacking a sound-only request returns the same output. Tests: `tests/compose/test_game_pack_audio.py` (sound-only requests in versions 1 and 2 with `assets` empty or absent write only the manifest, sound files and helper; manifest matches image packs except for empty `textures` and `animations`; sound files and helper match bytes; repacking returns identical results; requests with neither images nor sound are refused without creating an output directory for version 1 and version 2). Synthetic fixtures only.
+ - **New verb: `video-stop` cuts a walk or run that stops from the clip's own start played backwards.** Given the clip's keyed frames and a walk or run loop (`--frames-dir`, `--loop`), it writes a one-shot strip (`<name>.strip.png`), sidecar (`loop: false`, `hold_last: true`), GIF, WebP, and report (`<name>.stop.report.json`). The stop leaves the loop from the cell nearest the entry (`from_cell`), the first frame after the opening rest within `SAME_POSE` (0.35 steps) of a loop cell, and ends on the clip's first frame, the still as filmed. A seam past the jump line (1.4 steps, `--seam-max`) is refused by `video-stop` with exit code 1 and `status: "failed"` in the report, and so is another motion in the run-up between the rest and the entry, however short: a run-up frame back within `SAME_POSE` (0.35 steps) of a pose the clip had left by `TURN_BACK_AWAY` (one step) or more (the still, or the run-up's own), refused with "the run-up turns back — another motion, that the stop would play backwards", naming the three frames (`turn_back`, the nearest such comeback, is reported either way). A run-up longer than `RUN_UP_MAX_CYCLES` (1.5 cycles) — `source_cut.length` frames, overridden by `--run-up-max` — which plays strides unlike the loop's, is refused with "strides unlike the loop's, that the stop would play backwards"; `--run-up-max` bounds only that length and never lets another motion through. The seam refusal, the another-motion refusal and the run-up refusal can all be named in one message. Drift is taken out by laying the entry on its cell and the first frame on the loop's ground and mean coverage, moving frames between by a straight share of the difference per step; a run leaning away moves the still a few pixels, and drift not straight leaves a little of itself. Strips wider than 32,000 px are refused, `--speed 2` plays every other frame (still kept last), `--max-frames N` spaces frames evenly, and frames shown pass the ghost screen (`interpolation_quality`) as filmed. The pose thumbnails (`gait_fallback.poses`, 48 px cut about the feet) are now public, as the verb reads poses with them ([video-pipeline](docs/video-pipeline.md#8-a-walk-or-run-that-stops--video-stop)).
+ - **Fix: the poses of one image row keep one size and stay on their anchor.** Each pose of a row was shrunk into its cell on its own, so a raised or extended weapon shrank that pose's body (PR #107 gave the row one shrink ratio). That ratio fitted the widest pose by its own width, and `fit_to_cell` then placed it with its `align_x` anchor (the legs, by default) on the cell's centre line: a weapon held far out crossed the cell and the pose was pushed back in, body and all, so the body jumped back in that frame alone (a greatsword thrust: 39 px in a 256 cell). The ratio is now one function, `fit_scale`, which keeps every pose inside the safe area where its anchor puts it; `fit_to_cell` takes it for a frame alone, the row takes it over every pose, and `qa/inspect` fits a row the same way instead of pose by pose. With `bbox-center` nothing changes. A weapon held far to one side now costs size in a square cell: give such a row a wider cell ([pixel-unfake](docs/pixel-unfake.md)). Test: `tests/frames/test_row_scale.py`.
+ - **New: a motion plays as its request says — `--play loop|once-return|once-hold|lifetime` — and `video-set --motion` gives each state or item its own motion text.** A state's name used to fix its sentence, its end-frame pin, its cut and whether its strip loops, so every new motion (a punch, typing at a desk, a block, a tool swing) was a change to the engine. `video-set --play STATE=MODE` or `ITEM=MODE` and `video-prompt --play MODE` take the mode as a value of the request, and `video-set --motion STATE=TEXT` or `ITEM=TEXT` the caller's words in place of the state's sentence (an item's own value wins over its state's; a key that names neither, a key given twice or a mode the state cannot play is refused before any clip). A word the engine does not name is filmed under that name in that mode: a once-return is pinned to end on its first frame, asked for as one action that returns to the first pose, and cut whole by the new `video-loop --cycle once-return` (every frame, the last too, gated by the pin), its `strip.json` saying `loop: false`, `hold_last: false`, `returns: true` with the first pose in its first and last cells; a once-hold is cut at its held pose (`once`), the first settled pose whose drawing is not its first — a shield raised inside a body outline that keeps its size and floor is one, the first drawing come back, in place or slid sideways, is not — while the six terminal states keep their body-geometry screen (any other state cut `--cycle once` is screened by its drawing too); a lifetime is framed and filmed as an effect whatever its name; a loop asked for is searched as a loop (`periodic`) and never failed over to a single play. Named states are presets: without `--play` every state is filmed, prompted and cut as before, and an attack played once-return is the same prompt and the same pinned clip, cut whole and played once. `effect`, the six terminal states and the cyclic states refuse any other mode. `set.report.json` records each item's `play` (and `motion`); `video-prompt --json` records `play`. Not measured on a clip model: the sentences for a motion of your own ([video-pipeline](docs/video-pipeline.md#play-modes)).
+ - **Tests** — `tests/video/test_play.py` (every named state given no mode is pinned, prompted and cut as before, and the same when its preset is named, save that a loop asked for is never failed over; a mode a state cannot play is refused; a once-return asked for pinned with its return sentence and cut whole, or searched where the source cannot pin; the attack played once-return is the attack's prompt; a named state played another way takes the mode's sentence; a once-hold with its end frame; a once-hold of your own ending on a new drawing inside the same body box cut at its held pose, the same clip as `cast` still refused by its body geometry, and one that comes back to its first drawing, in place or slid sideways, refused; a lifetime filmed as an effect whatever its name; a loop of your own; `video-set` modes and texts per state and per item, refused before any clip when a key or mode is wrong; a once-return that does not come back refused; a once-return cut subsampled with both ends kept and played once; the CLIs) and the once-return item filmed end to end in `tests/video/test_clip_prompt.py`, its strip's first and last cells the first pose. Synthetic fixtures only.
+ - **Behavior change: the UI kit cut reads the drawing with one exact judgment instead of a centring heuristic.** Previously, each part went to the box that holds its centroid, with every box widened by half the gap. When that left a box empty, the layout was fitted to the drawing (least squares of box centres to the centres of what the boxes held, then assign again, at most 8 rounds) and kept when it left fewer required boxes empty, or as many and fewer boxes in all, reported as `layout_fit`. The only refusal of the cut was an empty frame. With several band elements missing on a drifted sheet, a drawn element could be cut under a neighbour's name, a drawn part named missing, or an undrawn element present; a drawing that fit the layout in two ways was cut silently under one of them; and a fit dragged by a small element placed off its box's centre gave wrong readings. The cut is the one reading within 1 px of the least cost, found by one exact search over the drifts the cut considers (a scale from 0.875 to 1.125 and an offset of at most 120 px at 1024), and every refusal comes from that one result ([ui-kit](docs/ui-kit.md#reading-the-drawing)). Every drawn element is cut under its own name, or the sheet is refused. A drawing that fits the layout in two ways is refused, naming both readings. New refusals: drifted further, ambiguous, off-centre, and off the layout. A sheet drawn on its guide is cut exactly as before, report bytes included. A sheet whose every part lies at least 1 px inside its box under some drift within the accepted range (along each axis a scale from 0.9 to 1.1 and an offset of at most 96 px at 1024), with all seven frames drawn, is cut exactly as drawn or refused as fitting the layout in two ways, never refused for another reason. A sheet with stray marks (parts in no box under the drift it was drawn with) is outside it.
+ - **Tests** — synthetic sheets cover the change: the two-way ambiguous sheet (512 × 768 px, seven 20 × 8 px frames, one dot on `pip_on` and squeezed `pip_off`) with an 18 px and a 60 px dot, refused by `split_ui_kit` and the CLI; the control sheet cut as `pip_off`; 512 sheets of small drawings and 256 sheets of full-size frames with small band drawings cut as drawn or refused as ambiguous, with three sheets previously refused as drifted now cut as drawn; each of the 256 sets of missing band elements under random accepted drifts; squeezes from the top by 0.90 to 0.99; a 17-sheet counterexample search; sheets refused as drifted further (20 % shorter), off-centre (dot in the gap), and required (each frame left out); a 2:3 sheet drawn on its guide with a mark 4 px wide and 20 px tall centred in the gap between the boxes of the two dots (`pip_on` above, `pip_off` below), refused as ambiguous (`pip_on, pip_off`); and 4 px scattered squares proved off the layout within 10 seconds. A square sheet and a 2:3 sheet drawn on their guide are cut byte for byte as before, with no `layout_fit`.
+ - **Fix: the test suite runs on Windows.** `pyproject.toml` named pytest-timeout's `signal` method, and Windows has no SIGALRM, so pytest stopped with an internal error before its first test unless `-o timeout_method=thread` was given. The method is now left to pytest-timeout, which takes `signal` where SIGALRM exists (Linux, macOS: unchanged) and `thread` on Windows. Test: `tests/packaging/test_project_metadata.py`. `tests/video/test_one_step_cut.py` skips where img2webp is missing, as the other loop tests do, instead of failing all twelve of its tests.
+ - **Fix: `sprite-gen prepare --request` keeps the request's `style`.** The subcommand declared its own copy of prepare's options, with `--style` defaulting to the default style sentence and `--cell-size` to 256, so a flag nobody gave counted as given: the request's `style` was replaced by the default sentence under a note that `--style, --cell-size` were given both ways (`scripts/prepare_sprite_run.py` and `prepare.run` were right). The subcommand now takes prepare's own declaration (`prepare.add_arguments`), which also gives it `--directions` and `--mirror`, missing until now. A request with no style and no cell still gets the default sentence and 256. Test: `tests/gen/test_flags_over_spec.py` (through `sprite-gen prepare`: a request alone keeps its style and cell with no note, a given `--style` wins and says so, the subcommand takes every option prepare declares).
+ - **New verb: `logo` makes a transparent typography logo from a mood image.** Lettering asked for alone comes back as a font with an effect; drawn into the picture it belongs to, it takes the scene's materials and light. `sprite-gen logo --text … --style …` letters the title (and an optional `--subtitle`, in an optional `--language`) into a 16:9 title screen or a 2:3 poster (`gen`), has the provider read its text back and refuses a title it dropped or misspelt before buying the next image, redraws only the lettering from that picture as an image edit on a chroma key (`gen --ref`), and cuts it out with the new logo matte, trimmed with a 2 px margin; the logo's text is read again and a logo whose letters differ is refused and kept aside as `logo.rejected.png`. Both checks compare what the text spells: every letter and digit and every mark written on one (an accent, a vowel sign, a virama), with case, compatibility forms, the characters drawn as nothing, enclosing marks, spaces, punctuation and symbols folded away. Files: `mood.png`, `lettering.png`, `logo.png`, `logo.preview.png` (the logo on a dark and a light backdrop) and `logo.report.json` (status, every step's prompt and numbers, the alpha coverage, the key hue left, both text checks, and every call with its `route`: `subscription` or `per-call`). `--mood` starts from a picture you have; `--lettering` cuts a lettering image again with nothing generated. `--chroma-key auto` scores both keys on the colours in the title's box (the mood check returns it): a letter in a key's hue counts against it, and a key wins by how long a glow's mix with it keeps its hue. Nothing in the path draws a font ([logo](docs/logo.md)).
+ - **New: the logo matte (`frames.logo_matte`) keeps a glow's fade and leaves no key hue.** The sprite matte ramps coverage over a short chroma distance, so on a white glow it is opaque half way to white with the pink mix of glow and key as its colour, and cuts the fade's last fifth to nothing. The logo matte measures the key as a quadratic surface with its noise, keeps material (far from the key, without its hue, minus rim pixels that are a mix of the key with the colour just inside) as drawn, gives a letter's antialiased edge its coverage on the letter's own colour, takes every other mix at the least coverage any colour could have, measures a glow's last trace on its faint neighbours, clears the faint seam a generated picture often has on its outer rows and columns, and writes each colour with the key's share taken out. Known limit: a glow carrying none of the key's hue, pooled dense and flat in a counter, is kept opaque; on the key whose hue it shares more it keeps its fade ([logo](docs/logo.md#known-limit)).
+ - **New: every provider's vision call takes the question asked (`inspect_image`).** The facing check's question and request body are unchanged; `logo` asks what the lettering spells, on the provider and credential that drew it.
+ - **Tests** — `tests/frames/test_logo_matte.py` (synthetic lettering with a known coverage and colour, no font drawn: solid letters opaque in their colour; a white glow's fade within 0.04 of the truth, never opaque short of 80 %, and its faint trace kept; no key hue on a dark or a light backdrop; a shaded key; an outlined letter with a cyan glow; a pooled cyan glow on green, and the known limit on magenta; the green key; pixel lettering hard-edged; a seam on the picture's edge; refusals of a border that is not the key and of an empty key; the trim, the coverage and the key choice), `tests/gen/test_logo.py` (the three steps through a stand-in provider: prompts, references, files and report; the text check on a plain backdrop; empty text refused before any call; a dropped title refused before the lettering; differing letters and no text refused with the cut kept aside; a check that could not run said, not passed; subtitle and language; `--mood`, `--lettering` in place, the key from the title box, an explicit key; no font drawn; a failed lettering leaves nothing in its place; a painted checkerboard refused; per-call routes; the comparison across scripts: a Devanagari vowel sign, virama or nukta, a Thai tone mark or a Latin accent dropped, or Arabic vowel marks changed, is a mismatch, and a vowel sign dropped is refused at both checks; Hangul as jamo or syllables, half-width katakana, a Roman numeral form, a variation selector, a keycap and a zero-width joiner are the same spelling) and `tests/gen/test_vision_read.py` (the question and detail carried on codex, grok and openai; the facing body unchanged).
+
- **Behavior change: `pixel-draw` runs on your Claude subscription first, and on `ANTHROPIC_API_KEY` only without one** — the order `codex` and `grok` keep. When `claude auth status` says Claude Code is signed in with a subscription (`claude.ai` or `oauth_token`), every call — the drawings, the row repairs, the pick — goes through the unmodified `claude` binary in print mode, from an empty directory, with no tool, no session written and no CLAUDE.md, hook, skill, plugin or MCP server loaded, and costs nothing per call: `report.json` says `auth_source: claude-login`, each call's `mode` is `subscription` and its `cost_usd` `0`, its usage kept. The child never sees `ANTHROPIC_API_KEY`, which print mode would use instead of the login. Without a subscription login the run uses the key as before, billed per call and said on stderr; with neither it is refused naming both, before the run folder is made. A login that refuses a call, has expired or has reached its usage limit fails the call; the run never switches to the key on its own. `--batch` is the API's Message Batches and runs on the key even when signed in. An answer the binary continues past the output cap is read whole from every message, not from its `result`, which holds only the last part; one it cannot finish is read as `stop_reason: max_tokens`, so the one redraw one effort lower happens on either route. One call may take up to `SPRITE_GEN_CLAUDE_CALL_TIMEOUT_SECONDS` (1800). When candidates ask at once, none of their requests leaves before the billing line has been printed. `report.json`'s `auth_source` is what the calls ran on by their records, `mixed` (with `auth_sources`) for a run resumed under the other credential. A `--resume` that reads every call back no longer prints the billing line ([pixel-draw](docs/pixel-draw.md#which-credential-a-call-runs-on)).
- **Behavior change: every metered call says so on the terminal, and every report names what a call ran on.** How codex is signed in is one reading, `codex_provider.codex_login` (`codex login status`), for the default provider resolution, `gen --provider codex`, the codex facing check and `workflow`: a codex signed in with an API key used to run with no word about it and the workflow called it a subscription; it now prints the per-call charge line before `codex exec` runs, its report records `extra.auth_source: codex-api-key` (`codex-login` on ChatGPT), and `workflow` asks to confirm the API credit. A codex that is not signed in is refused with the reason before it runs. `gen-set` and `video-set` keep each item's output in its log, but a child's billing line and a default provider switch now also print on the terminal as they happen (`base.run_logged`), each `gen-set` row records `auth_source`, and each `video-set` clip result too. `sound` prints the same billing line as every other metered route (it printed its own) and its receipt records `auth_source`. One function reads a provider key from the environment (`base.env_api_key`: a key, none, or a refusal of an empty one) for Anthropic, OpenAI, xAI and ElevenLabs; one function says what to do when xAI rejects a credential (`xai.rejected_fix`), so `gen --provider grok` now gives the same `grok models` refresh as `video`. `workflow` probes a provider once for its images and videos (they share one credential) and asks the API-credit question by that provider's name rather than always about Grok video. Docs: the credential table in the README, grok's `XAI_API_KEY` route in the help and SKILL.md, the sound billing line, `SPRITE_GEN_GEN_TIMEOUT_SECONDS` and `SPRITE_GEN_CLAUDE_READ_TIMEOUT_SECONDS`, and `gen-set --provider` (`codex` or `grok`).
- **Tests** — `tests/gen/test_claude_login.py` (the login before the key, the key only without a login, neither refused naming both, a batch on the key without asking the login, an unreadable status refused rather than read as no login, the child's environment without a key or the calling session, a message mapped onto the binary's flags and stdin with its image and schema, the stream-json answer, a cut answer read as max_tokens, a refused or limited login an error and not a switch to the key, no result, a timeout and a missing binary), the subscription, batch and read-back cases in `tests/gen/test_pixel_draw.py`, and `gen.base.env_api_key` in `tests/gen/test_gen.py`; `tests/gen/test_codex_login.py` (ChatGPT, an API key and not signed in; the default resolution, `generate` and `workflow` read the same login; an API-key login announces the charge and records it), `base.run_logged` in `tests/gen/test_gen.py`, the ElevenLabs billing line and key refusals in `tests/audio/test_sound.py`.
diff --cc docs/README.md
index 2e832a3,627f9a7..4c9b312
--- a/docs/README.md
+++ b/docs/README.md
@@@ -78,14 -78,15 +78,15 @@@ grouping is derived from `sprite_gen/_m
| Doc | Owns |
|---|---|
- | [gen.md](gen.md) | `sprite-gen gen` / `gen-set`: providers, default resolution, transparency strategy per provider, when a refused provider request is sent again, row usage |
+ | [gen.md](gen.md) | `sprite-gen gen` / `gen-set`: providers, default resolution and what a default codex that cannot run turns into, transparency strategy per provider, when a refused provider request is sent again, row usage |
| [`sprite-gen sound`](sound.md) | Generate normalized SFX and BGM audio assets with Opus and AAC encoding, SQLite raw request caching, and Web Audio loop metadata. |
| [pixel-draw.md](pixel-draw.md) | `sprite-gen pixel-draw` (experimental): Claude Opus draws 8–48 px pixel art as a pixel grid — the inputs, the safe area, the style (`--style`), a set of up to 64 frames drawn four at a time and one motion (`--motion`), the run folder and its report, gates G1–G8, the row repair and the one redraw, the pick between candidates, Message Batches and `--resume`, re-rendering an edited `grid.txt` |
+ | [logo.md](logo.md) | `sprite-gen logo`: a title logo or wordmark lettered by the model into a title screen or poster, only its lettering redrawn on a chroma key, cut out with its glow kept — the steps, files, report, text check and refusals, the key choice, the logo matte and its known limit |
| [prompt-assembly.md](prompt-assembly.md) | What the engine adds to a still or clip prompt and when: the pieces, the 2.22.0 freeze without `--handed`, what counts as already said, and the notes on the caller's own words |
| [video.md](video.md) | `sprite-gen video` / `video-extend` / `video-edit` / `video-resume`: stills and clips to mp4 through Grok Imagine (image-to-video, last-frame pin, references, extension, editing, asking again for an unfinished generation) with the user's own credential |
- | [video-pipeline.md](video-pipeline.md) | Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch, a set's directions on one sheet |
+ | [video-pipeline.md](video-pipeline.md) | Pipeline B engine contract: state canvas, keyed frames, true-period and one-shot cycles, strip/GIF/WebP, the batch, a set's directions on one sheet, a walk or run's stop |
| [loop-review.md](loop-review.md) | Automatic loop decisions, ambiguous gait review, visual evidence and explicit cut/alignment overrides |
-| [loop-repair.md](loop-repair.md) | RIFE (where it runs, cost, licences, `sprite-gen rife install`, what runs without it), jump-frame repair, the jolt index and its gate, one cycle length per direction set |
+| [loop-repair.md](loop-repair.md) | RIFE (where it runs, cost, licences, `sprite-gen rife install`, what runs without it), jump-frame repair, the flow reading (frames off a walk's way), the eased retime (a part that rushes on its way), the overlapped wrap (a part on its own beat at a two-step cut's wrap), the jolt index and its gate, one cycle length per direction set |
| [frame-interpolation.md](frame-interpolation.md) | Generative in-betweens for sprite frames, recorded as a take |
| [seamless-video-loop.md](seamless-video-loop.md) | Making a non-looping ambient clip loop forever (RIFE seam bridge) — a different job from pipeline B |
diff --cc sprite_gen/video/batch.py
index 8079cc0,f18884b..68b6544
--- a/sprite_gen/video/batch.py
+++ b/sprite_gen/video/batch.py
@@@ -804,8 -868,12 +868,12 @@@ def run_item
result["loop"]["motion_anchor"] = lp["motion_anchor"]
if "rife" in (lp.get("jump_repair") or {}):
# cut as filmed for want of RIFE: the set report lists it under `warnings`
- result["loop"]["jump_repair"] = {k: lp["jump_repair"][k] for k in ("applied", "why", "score_max_before", "install")}
+ result["loop"]["jump_repair"] = {k: lp["jump_repair"][k] for k in ("applied", "why", "off_max_before", "install")}
result["ok"] = True
+ except CodexUnavailableAsk as exc:
+ result["ok"] = False
+ result["asked"] = exc.question
+ result["error"] = f"the mid-step start still was not drawn: codex cannot run here ({exc.question['reason']})"
except SystemExit as exc:
result["ok"] = False
result["error"] = str(exc)
diff --cc sprite_gen/video/loop.py
index c01518b,048e610..49852be
--- a/sprite_gen/video/loop.py
+++ b/sprite_gen/video/loop.py
@@@ -1512,21 -1303,13 +1530,20 @@@ def run_loop
# The windows the wider search measured and refused go into the report's `cycle`.
if hasattr(second, "diagnostics"):
failed.diagnostics = second.diagnostics # type: ignore[attr-defined]
- raise failed from first
+ failed.__cause__ = first
+ refused, cycle = failed, None
if steps is not None:
+ # A count given is the word on the search's cut; the crossings are not asked.
+ if refused is not None:
+ raise refused
cycle = _counted(cycle, steps, window=window, D=D, trajectory=trajectory, frames=source_frames, moved=moved, detect=detect)
+ else:
+ cycle = _by_steps(cycle, refused, frames=source_frames, analysis=analysis, D=D, trajectory=trajectory,
+ window=window, searched=searched, detect=detect, seam_max=seam_max)
elif cycle_mode == "once":
source_frames = [Image.open(f).convert("RGBA") for f in files]
- boxes = [nonloop.body_box(frame) for frame in source_frames]
- cycle = nonloop.select_cut(D, masses, fps=fps,
- ending=partial(nonloop.hold_ending, boxes=boxes, state=state))
+ cycle = nonloop.select_cut(D, masses, fps=fps, ending=partial(
+ nonloop.hold_ending, pose=nonloop.end_pose(state, source_frames, _small_features)))
nonloop.validate_body(source_frames[cycle["start"]:cycle["end_frame"] + 1])
elif cycle_mode == "lifetime":
cycle = nonloop.select_cut(D, masses, fps=fps, kind=cycle_mode,
diff --cc sprite_gen/video/rife.py
index 83bf91f,a8af2d3..bf5cf51
--- a/sprite_gen/video/rife.py
+++ b/sprite_gen/video/rife.py
@@@ -30,8 -24,14 +30,15 @@@ puts it (`install_root()`, docs/loop-re
RIFE that is found and then fails is `RifeUnavailable` and always an error.
The interpolator is a plain callable `(a, b, t) -> frame`, so a caller can be handed a stand-in
-(`Interpolate`), and a test needs no binary.
+(`Interpolate`), and a test needs no binary. A caller that reads the passes takes a callable
+`(a, b, t) -> (frame, disagreement)` (`Read`, `Rife.read`).
+
+ A frame made between two frames can be kept and taken again (`Cache`): an alignment run twice on
+ the same source frames — again with the feet told — makes the same frames a second time, two RIFE
+ calls each (section 1 of docs/loop-repair.md has their cost; section 4 the cache). It is kept under
+ everything it is made from, the interpolator's `identity()` included — read again for every frame,
+ as the files a RIFE runs from can be written over under it — so it is taken only where making it
+ again would give the same bytes.
"""
from __future__ import annotations
@@@ -95,26 -79,17 +106,34 @@@ GHOST_THICK =
CROSSFADE_RANGE = 7
CROSSFADE_WINDOW = 0.08
CROSSFADE_KEEP = 0.6
-CALL_TIMEOUT_SECONDS = 120
+# `passes`: the binary's augmentation runs the pair turned eight ways (`-x`: every flip and transpose) and both ways in
+# time (`-z`), combines the sixteen inside, and gives back one frame — where the passes disagree, the frame does not say
+# so. Run one at a time with no augmentation, each turned back, they can be read apart. Each pass is two calls, colour
+# and coverage, as `between` makes them.
+PASS_GEOMETRIES = tuple((transpose, flips) for transpose in (False, True) for flips in range(4)) # flips: 1 left-right, 2 up-down
+PASS_CALLS = 2 * 2 * len(PASS_GEOMETRIES)
+# `torn`: the forward passes' mean and the backward passes' mean put a different colour or coverage at a pixel where
+# they are more than this apart (premultiplied RGBA, 0..1); an edge they place a pixel or two apart is thinner than
+# TORN_THICK pixels and opened away; a part torn is read in windows TORN_WINDOW of the body's height on a side, the
+# size of a hand on a walk.
+TORN_LEVEL = 0.05
+TORN_THICK = 3
+TORN_WINDOW = 0.10
+# One call past this is stopped and reported as a RIFE that failed. TTA's slowest call measured, on a
+# 960 x 960 frame on Modal's CPU, took about 30 s, and Modal's hosts differ by up to 2.5 times on one frame
+# (2026-10-15, docs/loop-repair.md section 1).
+CALL_TIMEOUT_SECONDS = 600
+ # `Cache`: the first thing a kept frame's key is made from — another way of keying or keeping frames is another
+ # name, so no frame kept the old way is taken — and the PNG text a kept frame names its own pixels' sha256 under.
+ CACHE_FORMAT = "sprite-gen frame between, 1"
+ PIXELS_TEXT = "sprite-gen-pixels-sha256"
+ # The engine code that makes a frame between, as this process loaded it (`Rife.identity`): read once, at import —
+ # rife.py written over on disk later changes no code that runs here, so a frame made here is kept under the code that
+ # made it, and a process that loads other code makes it again.
+ CODE_SHA256 = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
Interpolate = Callable[[Image.Image, Image.Image, float], Image.Image]
+Read = Callable[[Image.Image, Image.Image, float], tuple[Image.Image, np.ndarray]]
# The one line that installs it, quoted wherever a missing RIFE is reported.
INSTALL_COMMAND = "sprite-gen rife install"
@@@ -209,12 -168,13 +228,16 @@@ def _call(binary: Path, model: Path, a
out.unlink(missing_ok=True)
try:
proc = subprocess.run(
- [str(binary), "-0", str(tmp / "a.png"), "-1", str(tmp / "b.png"), "-o", str(out), "-s", f"{t:.4f}", "-m", str(model)],
+ [str(binary), "-0", str(tmp / "a.png"), "-1", str(tmp / "b.png"), "-o", str(out), "-s", f"{t:.4f}", "-m", str(model), *modes],
capture_output=True, text=True, timeout=CALL_TIMEOUT_SECONDS,
)
+ except subprocess.TimeoutExpired as exc:
+ raise RifeUnavailable(f"{binary.name} made no frame in {CALL_TIMEOUT_SECONDS} s and was stopped "
+ f"(augmentation {' '.join(modes) or 'none'}, SPRITE_GEN_RIFE_TTA)") from exc
+ except OSError as exc:
+ # A binary that is found but cannot be started (a damaged or wrong-platform build:
+ # WinError 193 on Windows, ENOEXEC elsewhere) is a RIFE that fails, not a crash.
+ raise RifeUnavailable(f"{binary.name} could not be started: {exc}") from exc
if proc.returncode != 0 or not out.is_file():
raise RifeUnavailable(f"{binary.name} failed (exit {proc.returncode}): {(proc.stderr or proc.stdout).strip()[-300:]}")
with Image.open(out) as im:
@@@ -495,32 -332,16 +518,40 @@@ def crossfade(made: Image.Image, a: Ima
return round(lost / max(1, int(solid.sum())), 5)
+def torn(apart: np.ndarray, made: Image.Image) -> float:
+ """A part torn in a made frame, read on how far its single passes disagree (`passes`): of the pixels where they are
+ more than TORN_LEVEL apart, those in regions at least TORN_THICK pixels thick, and of them the largest share of a
+ window TORN_WINDOW of the made frame's body height on a side (8 px at least; the windows step by a quarter of it). A
+ hand the flow drags apart beside a tail swung far fills its window; an edge the passes place a pixel apart, or hair
+ they redraw strand by strand, leaves it nearly empty. Read in a window, not over the body, so a small part torn on a
+ large body is not lost in it. 0 where the frame has no solid body (docs/loop-repair.md section 4)."""
+ alpha = np.asarray(made.convert("RGBA").getchannel("A"), dtype=np.float32) / 255.0
+ rows = np.nonzero((alpha >= 0.5).any(axis=1))[0]
+ if rows.size == 0:
+ return 0.0
+ side = max(8, int(round((rows[-1] - rows[0] + 1) * TORN_WINDOW)))
+ thick = _mask(_mask(apart > TORN_LEVEL, TORN_THICK, ImageFilter.MinFilter), TORN_THICK, ImageFilter.MaxFilter)
+ h, w = thick.shape
+ if side >= min(h, w):
+ return round(float(thick.sum()) / (side * side), 5)
+ sums = np.pad(thick.astype(np.float64).cumsum(axis=0).cumsum(axis=1), ((1, 0), (1, 0)))
+ step = max(1, side // 4)
+ ys, xs = np.arange(0, h - side + 1, step)[:, None], np.arange(0, w - side + 1, step)[None, :]
+ covered = sums[ys + side, xs + side] - sums[ys, xs + side] - sums[ys + side, xs] + sums[ys, xs]
+ return round(float(covered.max()) / (side * side), 5)
+
+
+ def _file_sha256(path: Path) -> str:
+ h = hashlib.sha256()
+ with path.open("rb") as f:
+ for block in iter(lambda: f.read(1 << 20), b""):
+ h.update(block)
+ return h.hexdigest()
+
+
class Rife:
- """A located RIFE as an `Interpolate` callable. Counts the frames it made (`made`)."""
+ """A located RIFE as an `Interpolate` callable, and as a `Read` (`read`). Counts the frames it made (`made`) and the
+ times it ran the binary (`calls`)."""
def __init__(self, binary: Path | None = None, model: Path | None = None):
if binary is None or model is None:
@@@ -534,18 -353,115 +565,126 @@@
with tempfile.TemporaryDirectory(prefix="sprite-gen-rife-") as td:
frame = between(a, b, t, binary=self.binary, model=self.model, tmp=Path(td))
self.made += 1
+ self.calls += 2
return frame
+ def read(self, a: Image.Image, b: Image.Image, t: float) -> tuple[Image.Image, np.ndarray]:
+ """The frame at `t`, made as every call makes it (`between`), and how far the sixteen single passes disagree
+ there (`passes`): 2 + PASS_CALLS calls of the binary."""
+ with tempfile.TemporaryDirectory(prefix="sprite-gen-rife-") as td:
+ frame = between(a, b, t, binary=self.binary, model=self.model, tmp=Path(td))
+ apart = passes(a, b, t, binary=self.binary, model=self.model, tmp=Path(td))
+ self.made += 1
+ self.calls += 2 + PASS_CALLS
+ return frame, apart
+
def describe(self) -> dict[str, str]:
- return {"binary": str(self.binary), "model": self.model.name}
+ return {"binary": str(self.binary), "model": self.model.name, "tta": " ".join(self.tta)}
+
+ def identity(self) -> str:
+ """What a frame this RIFE makes depends on besides its two frames and t, as one string (`Cache` keys
+ on it), read as it is now on every call — nothing of it is kept, so a binary, model or machine changed
+ under this very RIFE is another identity: the binary's and each of the model's files by sha256, and the
+ model's path as the binary is handed it (the binary reads the model's version from its name); the engine
+ code this process loaded (`CODE_SHA256`: it turns a frame into RIFE's two runs and back) and NumPy's and
+ Pillow's versions; and the machine — the OS, and `uname`'s host name, OS release and build and
+ architecture (platform.uname() keeps its first answer) — as the Apple GPU and llvmpipe are only measured
+ to agree to the third decimal of an error (docs/loop-repair.md section 1), so a frame made on one is not
+ taken on another. Files that cannot be read are a RIFE that fails (`RifeUnavailable`)."""
+ try:
+ model = sorted(p for p in self.model.iterdir() if p.is_file())
+ files = {"binary": _file_sha256(self.binary), "model": str(self.model), "model_files": {p.name: _file_sha256(p) for p in model}}
+ except OSError as exc:
+ raise RifeUnavailable(f"{self.binary.name}: the binary or model it runs from could not be read: {exc}") from exc
+ return json.dumps({
+ **files, "code": CODE_SHA256, "numpy": np.__version__, "pillow": PIL.__version__,
+ "machine": [sys.platform, *(os.uname() if hasattr(os, "uname") else platform.uname()[:5])]}, sort_keys=True)
+
+
+ def _kept(path: Path, size: tuple[int, int]) -> Image.Image | None:
+ """The frame kept at `path`, or None where it is not one: not a PNG, not RGBA at `size`, cut short, or
+ its pixels not the ones its PIXELS_TEXT names."""
+ try:
+ with Image.open(path) as im:
+ if im.format != "PNG" or im.mode != "RGBA" or im.size != size:
+ return None
+ im.load()
+ data, named = im.tobytes(), im.info.get(PIXELS_TEXT)
+ except (OSError, SyntaxError, ValueError, EOFError):
+ return None
+ if named != hashlib.sha256(data).hexdigest():
+ return None
+ return Image.frombytes("RGBA", size, data)
+
+
+ class Cache:
+ """Frames made between two frames, kept in `directory` and taken from there when the same frame is
+ asked for again (`video-cycle-align --between-cache`, docs/loop-repair.md section 4).
+
+ A frame is kept under the sha256 of everything it is made from: CACHE_FORMAT, the interpolator's
+ `identity()`, each of the two frames' mode, size and bytes, and `t` exactly. Another frame, fraction,
+ RIFE or machine is another key, so a frame kept for other inputs is never taken. The key is read
+ for every frame asked for, and once more after a frame is made: a frame made while what it is made
+ from changed (a binary or model written over between RIFE's two runs) is handed on as made but not
+ kept, as no key names what made it, counted `not_kept`. Frames are kept for RGBA frames only: their
+ mode, size and bytes are all of them, where a palette or a transparent colour is not in an image's
+ bytes. A kept frame is a PNG naming its own pixels' sha256, written whole or not at all; a file that
+ does not read back as that frame (cut short, written over) is made again and kept over it, counted
+ `unreadable`. A frame taken is a new image of the kept pixels, as the interpolator's own frame is.
+
+ Nothing is kept unless a caller names the directory, and nothing here removes it: it belongs to the
+ caller, who gives each alignment its own. It is created readable by this user only. Counts the frames
+ taken (`hits`) and made (`misses`)."""
+
+ def __init__(self, directory: Path):
+ self.directory = Path(directory).expanduser().resolve()
+ self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
+ self.hits = self.misses = self.unreadable = self.not_kept = 0
+
+ def key(self, interpolate: Interpolate, a: Image.Image, b: Image.Image, t: float) -> str:
+ for f in (a, b):
+ if f.mode != "RGBA":
+ raise ValueError(f"rife: a frame between is kept for RGBA frames only, not {f.mode}: a palette or a "
+ "transparent colour is not in an image's bytes, which are what it is kept under")
+ h = hashlib.sha256()
+ for part in (CACHE_FORMAT, interpolate.identity(), a.mode, *map(str, a.size), b.mode, *map(str, b.size), float(t).hex()): # type: ignore[attr-defined]
+ h.update(part.encode() + b"\0")
+ h.update(a.tobytes())
+ h.update(b.tobytes())
+ return h.hexdigest()
+
+ def frame(self, interpolate: Interpolate, a: Image.Image, b: Image.Image, t: float) -> Image.Image:
+ """The frame at `t` between `a` and `b`: the one kept for exactly these, else `interpolate`'s — kept where
+ its key reads the same once it is made."""
+ key = self.key(interpolate, a, b, t)
+ path = self.directory / f"{key}.png"
+ if path.exists():
+ kept = _kept(path, a.size)
+ if kept is not None:
+ self.hits += 1
+ return kept
+ self.unreadable += 1
+ made = interpolate(a, b, t)
+ if made.mode != "RGBA" or made.size != a.size:
+ raise ValueError(f"rife: a frame between is kept as RGBA at its frames' size {a.size}, not {made.mode} at {made.size}")
+ self.misses += 1
+ if self.key(interpolate, a, b, t) != key:
+ self.not_kept += 1
+ return made
+ # saved from a copy of its pixels, so the frame handed on carries nothing of this save
+ pixels = made.tobytes()
+ info = PngImagePlugin.PngInfo()
+ info.add_text(PIXELS_TEXT, hashlib.sha256(pixels).hexdigest())
+ fd, staged = tempfile.mkstemp(prefix=".", suffix=".tmp", dir=self.directory)
+ try:
+ with os.fdopen(fd, "wb") as out:
+ Image.frombytes("RGBA", made.size, pixels).save(out, format="PNG", pnginfo=info)
+ os.replace(staged, path)
+ except BaseException:
+ Path(staged).unlink(missing_ok=True)
+ raise
+ return made
+
+ def record(self) -> dict[str, object]:
+ return {"dir": str(self.directory), "hits": self.hits, "misses": self.misses, "unreadable": self.unreadable,
+ "not_kept": self.not_kept}
diff --cc tests/conftest.py
index cd93e9a,0fe3efe..d458133
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@@ -116,19 -124,16 +132,29 @@@ def pytest_make_collect_report(collecto
return report
+@contextmanager
+def feet_unseen() -> Generator[None, None, None]:
+ """`video-loop`'s step count reads no feet (sprite_gen/video/crossings.py): the cut is the pixel search's alone.
+ For the tests of that search, whose walker is drawn for it — legs that open and close once a drawing and never
+ pass each other, a scissor no walk makes, which the count reads as one step a drawing — and of the step screen,
+ the word where a clip does not show its steps."""
+ from sprite_gen.video import crossings
+
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(crossings, "read", lambda sig: crossings.Reading(len(sig["gap"]), "gap", [], why="the feet read as unseen (test)"))
+ yield
+
+
+ @pytest.fixture(autouse=True)
+ def own_settings(tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch) -> None:
+ """No test reads the saved preferences or the provider choices of the machine it runs on: what a call that
+ names no provider runs on (SPRITE_GEN_DEFAULT_PROVIDER) and what a default codex that cannot run turns into
+ (SPRITE_GEN_CODEX_UNAVAILABLE, `sprite-gen defaults`) are each test's own. Child processes inherit both."""
+ monkeypatch.setenv("SPRITE_GEN_CONFIG_DIR", str(tmp_path_factory.mktemp("sprite-gen-config")))
+ for name in ("SPRITE_GEN_DEFAULT_PROVIDER", "SPRITE_GEN_CODEX_UNAVAILABLE"):
+ monkeypatch.delenv(name, raising=False)
+
+
@pytest.fixture
def fixture_run_dir(tmp_path: Path) -> Path:
"""A throwaway copy of the golden fixture run dir."""
diff --cc tests/video/test_loop_repair.py
index f24bf83,85175d2..0ecd2a5
--- a/tests/video/test_loop_repair.py
+++ b/tests/video/test_loop_repair.py
@@@ -229,27 -187,15 +229,34 @@@ def test_video_loop_records_the_repair_
assert np.array_equal(np.asarray(Image.open(tmp_path / "out" / "cycle" / "frame-009.png")), np.asarray(reopened[9]))
assert json.loads((tmp_path / "w.json").read_text())["jump_repair"]["replaced"] == [10]
assert made == [0.5]
+ # the jolt of the loop as it plays after the repair (docs/loop-repair.md section 3)
+ jolt = rep["jolt"]
+ assert jolt["measured"] == "after the jump repair" and jolt["warnings"] == [] and jolt["passed"]
+ assert jolt["gated"] is False and jolt["gate"] is None
+ assert jolt["reference"] == {"jolt_max": repair.JOLT_REFERENCE, "head_step_max": repair.HEAD_STEP_REFERENCE}
+ assert set(jolt["head"]["x"]) >= {"step_max_pct", "step_median_pct", "max_over_median", "range_pct"}
+ assert set(jolt["head"]["y"]) >= {"step_max_pct", "step_median_pct", "max_over_median", "range_pct"}
+def test_video_loop_plays_two_frames_made_again_at_their_own_times_in_a_loop_as_long(tmp_path):
+ filmed, truth = _loop({8: 14, 9: 14})
+ keyed = _keyed(tmp_path, filmed)
+ made = []
+
+ def between(a, b, t):
+ made.append(round(t, 4))
+ return truth[8] if t < 0.5 else truth[9]
+
+ rep = _run(tmp_path, keyed, interpolate=between)
+ assert rep["jump_repair"]["replaced"] == [8, 9] and made == [0.3333, 0.6667]
+ (round_,) = [r for r in rep["jump_repair"]["rounds"] if r["why"] == "flow"]
+ assert round_["neighbours"] == [7, 10] and round_["t"] == [0.3333, 0.6667]
+ cells = sorted((tmp_path / "out" / "cycle").glob("frame-*.png"))
+ assert len(cells) == N # the loop keeps its length: each frame its own time
+ for k in (8, 9):
+ assert np.array_equal(np.asarray(Image.open(cells[k])), np.asarray(truth[k]))
+
+
def _no_rife(monkeypatch, tmp_path: Path) -> None:
"""No RIFE anywhere the engine looks: no SPRITE_GEN_RIFE, an empty PATH, an empty data directory."""
monkeypatch.delenv("SPRITE_GEN_RIFE", raising=False)
diff --cc tests/video/test_one_step_cut.py
index b1e92a3,821fe2c..d477ea0
--- a/tests/video/test_one_step_cut.py
+++ b/tests/video/test_one_step_cut.py
@@@ -25,8 -21,12 +25,13 @@@ from pathlib import Pat
import pytest
from PIL import Image, ImageDraw
+from conftest import feet_unseen
from sprite_gen.video import align, batch, loop, period
+ from tests.video.test_video_pipeline import HAS_IMG2WEBP
+
+ # Every test here cuts a loop, and a loop is written with img2webp: without it they skip, as the
+ # other loop tests do, rather than fail.
+ pytestmark = pytest.mark.skipif(not HAS_IMG2WEBP, reason="img2webp not installed")
CYCLE, FRAMES = 42, 73