All 48 libraries

SugarAnimation

ANSI/GIF animation toolkit

inspired by namzug16/gifterm gif ascii-art ext-gd truecolor

SugarAnimation code coverage

SugarAnimation is an ANSI/GIF animation toolkit for PHP 8.3+. It decodes a .gif from disk with ext-gd, area-averages each frame onto a fixed cell grid, and paints it with 24-bit ANSI color. It also parses and replays truecolor .ansi art files frame by frame, which needs no GD at all. The GIF path is inspired by the Go project gifterm; the library itself is native PHP. The ready-made viewer CLI ships separately as candy-gifview.

Install

composer require sugarcraft/sugar-animation

Requires PHP 8.3 or newer. ext-gd is needed only for the GIF path (Decoder). AnsiArt, ArtLibrary, ArtLoop and Player run without it. Without GD, Decoder::decode(), Decoder::decodeFile() and Decoder::decodeBytes() throw a RuntimeException that names the missing extension. Decoder::readFile() and Decoder::loopCount() do not use GD and keep working.

Quickstart

// Decode a GIF from disk and play it in the alternate screen.
// "cat.gif" is any .gif on disk.
use SugarCraft\Core\Program;
use SugarCraft\Core\ProgramOptions;
use SugarCraft\Animation\Decoder;
use SugarCraft\Animation\Player;

$frames = Decoder::decode('cat.gif', cellsW: 80, cellsH: 30);
(new Program(new Player($frames),
             new ProgramOptions(useAltScreen: true)))->run();
// .ansi art: parse once, then print one frame as SGR text.
use SugarCraft\Animation\AnsiArt;

$art = AnsiArt::fromFile('logo-neon-tc-72x9.ansi');
echo $art->sgrText(0), PHP_EOL; // animated files: pick a frame index
# The viewer CLI is a separate app package:
#   composer require sugarcraft/candy-gifview
#   candy-gifview my-animation.gif           # solid blocks (default)
#   candy-gifview my-animation.gif density   # luminance ramp

To see the whole pipeline without any file of your own, run examples/play.php (see Examples below).

Concepts

The library has two halves that share a cell model. The GIF half turns bytes into Frame values. A Frame is a grid of RGB cells (null marks a transparent cell), a centisecond delay, a disposal method and a transparency flag. Decoder walks the GIF stream, hands each image to GD, and area-averages the source pixels under each cell with CellSampler. The grid size is fixed at decode time, so the art is stretched to exactly cellsW by cellsH cells and is never re-fit to the terminal.

The playback half is a TEA model. Player implements the sugar-core Model contract. It advances on TickMsg values scheduled with Cmd::tick(), so no fiber busy-waits. Renderer turns one frame into an ANSI string with one of two presets: solid paints full cells with a 24-bit background, and density maps each cell's luminance to a glyph from a ramp with a 24-bit foreground.

The .ansi half is separate. AnsiArt parses a byte stream of SGR runs and glyphs into cell-grid frames, ArtLibrary indexes a corpus of pre-authored files, and ArtLoop converts elapsed seconds into a frame index for banners and logos.

Tasks

Decode a GIF to a fixed grid. Call Decoder::decode($path, $cellsW, $cellsH) for a plain list<Frame>. Use Decoder::decodeFile() when you also need the loop count and the stop reason in one value.

Start paused and step by hand. Pass paused: true to the Player constructor. Then use the arrow keys to move one frame at a time.

Bound a run. Chain playOnce(), withLoops(3) or withMaxSeconds(10.0) on the Player. Each returns a new instance.

Pin the frame rate. Call withFixedFps(12.0) to advance on a uniform wall-clock cadence instead of the per-frame GIF delays.

Choose the viewport-fit renderer. Pass Renderer::withAdaptiveSize() to the Player constructor. It reads the terminal size from STDOUT with PosixBackend::queryWinsize(1) and clips the art to the viewport. It throws a RuntimeException when STDOUT is not a terminal, so guard the call in piped output or CI and fall back to Renderer::new(). Pass Renderer::withAdaptiveSize(reservedRows: 2) to leave rows free for your own chrome.

Pick a logo variant by terminal depth. Build an ArtLibrary with ArtLibrary::fromDir($dir), then call pick($slug, $depthTag). The requested depth is tried first. If the slug has no variant at that depth, the adjacent depths are tried in a fixed order: a tc request falls back to 256 then 16, a 256 request to tc then 16, and a 16 request to 256 then tc.

What's in the box

ext-gd decodeWalks the GIF byte stream for image-descriptor offsets, hands each frame to GD, and area-averages it onto the cell grid.
Area-average downsamplingEach cell averages the fully opaque source pixels that cover it. The palette path skips pixels that match the transparent index.
ASCII luminance rampThe density preset maps each cell's luminance (0.299r + 0.587g + 0.114b) to a ramp glyph and carries the color as a 24-bit foreground, so the shape still reads where color is stripped.
Local color tablesEach frame uses its own Local Color Table when the Image Descriptor carries one, and falls back to the Global Color Table otherwise.
Transparency and disposalThe Graphic Control Extension supplies the transparent index and disposal method (none, restore to background, restore previous), tracked per frame in Frame.
Two presetssolid paints full cells with a 24-bit background and a space glyph. density uses the ramp ' .:-=+*#%@' with a 24-bit foreground.
Viewport-fit renderingRenderer::withAdaptiveSize() reads the terminal size from STDOUT through PosixBackend::queryWinsize(1) (TIOCGWINSZ) and clips the art. It throws when STDOUT is not a terminal. A resize clips the art; it never re-scales it.
.ansi art playbackTruecolor .ansi streams parse into cell-grid frames with AnsiArt. ArtLibrary selects a variant for the detected depth, and ArtLoop cycles frames by elapsed time.
Bounded playbackplayOnce(), withLoops(n) and withMaxSeconds(s) cap a run. withFixedFps() pins the cadence.
Decode capsOne decode holds at most 256 frames (Decoder::MAX_FRAMES), 2,000,000 source pixels (MAX_TOTAL_PIXELS) and 100,000 output cells per frame (MAX_CELLS). A cap breach throws. The file entry points read at most one byte past Decoder::MAX_INPUT_BYTES (64 MiB), then refuse any file that is larger.

API

CallSignatureDescription
Decoder::decode()decode(string $path, int $cellsW, int $cellsH): arrayDecode a GIF file into a list<Frame>, stretched to exactly cellsW by cellsH. Throws on a cap breach, a missing ext-gd, or non-GIF input.
Decoder::decodeFile()decodeFile(string $path, int $cellsW, int $cellsH, bool $withCanvasRgba = false): DecodedAnimationDecode a file and return frames, the loop count and the walk's stop reason in one value.
Decoder::decodeBytes()decodeBytes(string $bytes, int $cellsW, int $cellsH, bool $withCanvasRgba = false): \GeneratorDecode bytes you already hold, yielding one Frame at a time. Pass true to carry full-canvas RGBA per frame.
Decoder::readFile()readFile(string $path): stringRead a file into bytes. It pulls at most MAX_INPUT_BYTES + 1 bytes and throws when the file is larger than MAX_INPUT_BYTES.
Decoder::loopCount()loopCount(string $bytes): ?intRead the NETSCAPE loop count. null or 0 means loop forever.
Frame::new()new(array $cells, int $delay = 10, int $disposal = Frame::DISPOSAL_NONE, bool $transparent = false, ?string $rgba = null, int $rgbaWidth = 0, int $rgbaHeight = 0)Value object for one frame: its cells, centisecond delay, disposal method, transparency and optional RGBA.
DecodedAnimation::frames()frames(): arrayThe decoded frames. loopPlays(), truncated() and stopReason() report the loop policy and whether the walk stopped early.
Player::__construct()__construct(array $frames, int $index = 0, bool $paused = false, string $preset = Renderer::PRESET_SOLID, ?Renderer $renderer = null, ?float $fixedFps = null, ?float $maxSeconds = null, ?int $loops = null)Create the playback TEA model. Named arguments are the usual way to set the options.
Player::withFixedFps()withFixedFps(float $fps): selfAdvance on a uniform cadence. The value must be positive and finite. Rates above Player::MAX_FPS (100,000) clamp to that ceiling.
Player::withMaxSeconds()withMaxSeconds(float $seconds): selfStop after the given number of seconds.
Player::withLoops()withLoops(?int $plays): selfStop after the given number of playthroughs. null, the default, loops forever. Stops on the tick that crosses the last lap, with no wall-clock timer armed.
Player::playOnce()playOnce(): selfPlay a single pass, then stop.
Player::withFrames()withFrames(array $frames): selfRebind the frame stream on a new instance.
Player::withWatch()withWatch(\Closure $probe): selfInstall a reload probe that the player polls on a timer.
Renderer::new()new(): selfUnconstrained renderer.
Renderer::withAdaptiveSize()withAdaptiveSize(int $reservedRows = 0): selfRenderer that queries the terminal size and clips output to it.
Renderer::withConstraints()withConstraints(int $rows, int $cols): selfRenderer with a fixed row and column budget.
Renderer::renderFrame()renderFrame(Frame $f, string $preset = Renderer::PRESET_SOLID): stringRender one frame to an ANSI string, clipped to the budget.
AnsiArt::fromFile()fromFile(string $path): selfParse a .ansi file. It reads at most Decoder::MAX_INPUT_BYTES + 1 bytes and refuses a larger file.
AnsiArt::fromString()fromString(string $bytes): selfParse .ansi bytes you already hold. Input larger than Decoder::MAX_INPUT_BYTES (64 MiB) is refused.
AnsiArt::frameCells()frameCells(int $frame): arrayThe AnsiCell grid for one frame.
AnsiArt::sgrText()sgrText(int $frame): stringCanonical SGR replay text for one frame. Escapes that the input carried are not replayed.
AnsiArt::width()width(): intWidth of the art in cells.
AnsiArt::height()height(): intHeight of the art in cells.
AnsiArt::frameCount()frameCount(): intNumber of frames. A static file has one frame.
AnsiArt::isAnimated()isAnimated(): boolTrue when the file carries more than one frame.
AnsiCell::new()new(string $glyph, string $sgr = ''): selfOne cell: its glyph and its canonical whole-state SGR.
ArtLibrary::fromDir()fromDir(string $dir, bool $includeSkinny = false): selfIndex a .ansi corpus from a directory.
ArtLibrary::pick()pick(string $slug, string $depthTag, bool $preferAnimated = true): ?AnsiArtSelect a slug at the requested depth. If that depth has no variant, the adjacent depths are tried in cascade order: tc then 256 then 16 for a tc request, 256 then tc then 16 for a 256 request, and 16 then 256 then tc for a 16 request.
ArtLibrary::randomSlug()randomSlug(string $depthTag, bool $preferAnimated = true, ?callable $rng = null): ?stringPick a random slug that the depth tag supports.
ArtLibrary::mergeManifest()mergeManifest(string $jsonlPath): selfAdd the entries from a JSONL manifest to the index.
ArtLoop::new()new(int $frameCount, float $frameSeconds = 0.1, float $pauseSeconds = 2.5): selfCycle frames by elapsed seconds, with a pause between cycles.
ArtLoop::frameAt()frameAt(float $elapsedSeconds): intFrame index for an elapsed time.

Only methods declared in sugar-animation/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\Animation

AnsiArt final class

A parsed .ansi ANSI-art document (the candy-top logo corpus format).

MethodSummary
static fromString(string $bytes): self
static fromFile(string $path): self
width(): intMax cell count over every row of every frame (half-blocks are single cells).
height(): intRow count of frame 0; redraw frames are assumed full-height by the corpus.
frameCount(): int
isAnimated(): bool
frameCells(int $frame): arrayRows of cells for one frame. Row lengths are kept NATURAL (ragged): trailing default-background spaces are absent in the corpus, and padding them would invent cells the artwork never painted.
sgrText(int $frame): stringRaw single-frame byte blob for apps that prefer replaying escapes verbatim instead of walking cells. Each cell carries a canonical WHOLE-state run, so a state change re-emits ESC[0m first (clearing components the next state omits) followed by the new canonical run; a change from default needs no reset, and each row plus the blob end in default state. The result is terminal-correct as replay AND cell-exactly re-parseable by fromString() — the accumulator reproduces every canonical whole-state run byte-for-byte, so the per-cell model and the raw stream stay in lockstep.

AnsiCell final class

One rendered terminal cell of a parsed .ansi artwork: the glyph plus the CANONICAL RESOLVED SGR state active for it — the full cumulative ECMA-48 style (attributes + foreground + background) a real terminal would be showing at that point, as a single ESC[…m run in the fixed order documented on AnsiArt::canonicalSgr(); '' when every component is at terminal default.

MethodSummary
static new(string $glyph, string $sgr = ''): selfHouse factory convention (::new()), mirroring the sugar-style immutable value-object shape.

ArtLibrary final class

Catalog over a directory of candy-top logo .ansi files, named logo-<slug>[-skinny][-anim]-<16|256|tc>-<WxH>.ansi.

MethodSummary
static fromDir(string $dir, bool $includeSkinny = false): selfIndex every matching art file in $dir. Unparsable names are skipped silently — a logo directory accumulates scratch files, and the catalog should degrade to the valid subset rather than fail the whole app.
static profileTag(ColorProfile $profile): stringMap a detected terminal colour profile onto this corpus's depth tags.
mergeManifest(string $jsonlPath): selfAttach per-slug description/tags from a logos.jsonl manifest. Tolerant by design: a missing/unreadable file or malformed rows is a no-op, because the manifest is optional human metadata shipped alongside the corpus, never a load-bearing dependency. The tolerance is paid with a bound — the read is capped at MAX_MANIFEST_BYTES, and a manifest beyond the gate is skipped exactly like an absent one (no throw, no partial enrichment, no unbounded slurp of a file we were going to distrust anyway).
slugs(): array
entries(): array
description(string $slug): string
tags(string $slug): array
pick(string $slug, string $depthTag, bool $preferAnimated = true): ?AnsiArtResolve a slug at a depth with the cascade: preferred-kind@depth -> other-kind@depth -> preferred-kind@adjacent-first other depth -> other-kind@same, completing every rung of the wide render before the skinny axis is consulted (a slug present in both forms always prefers NON-skinny; the depth cascade never crosses the skinny axis). "preferred kind" is animation when $preferAnimated, else static. Returns null only when the slug is unknown entirely.
randomSlug(string $depthTag, bool $preferAnimated = true, ?callable $rng = null): ?stringUniform over slugs that have ANY cascaded entry at the depth family.
pickRandom(string $depthTag, bool $preferAnimated = true, ?callable $rng = null): ?AnsiArt

ArtLoop final class

Pure frame-pacing math for animated ANSI art. The .ansi corpus carries no per-frame delays (see AnsiArt), so playback speed is a caller policy: each frame shows for $frameSeconds, and the LAST frame is then held an extra $pauseSeconds before the loop restarts at frame 0 — the beat where the animation "breathes" on screen.

MethodSummary
static new(int $frameCount, float $frameSeconds = 0.1, float $pauseSeconds = 2.5): self
withPause(float $pauseSeconds): selfFluent pause variant — the dwell on the last frame is the usual tuning knob.
cycleSeconds(): floatOne full lap: every frame once, plus the closing hold on the last.
frameAt(float $elapsedSeconds): intWhich frame is on screen at an elapsed offset. Boundaries land on the later frame (a frame owns [start, start+duration) ).

DecodedAnimation final class

The whole canonical decode as one value (SA-G1 -006).

MethodSummary
frames(): array
loopPlays(): ?intTotal playthroughs, null = loop forever (see class docblock).
truncated(): boolMay the frame list be hiding frames? True exactly when the walk carries a stop reason — either the frame cap withheld later frames (including the documented exactly-256 false positive) or an advertised frame was skipped undecodable.
stopReason(): ?string

Decoder final class

Decode a GIF — from disk via self::decode() or in-memory via self::decodeBytes() (E-07) — into Frames, using ext-gd's imagecreatefromstring() for in-memory single-frame extraction and a hand-rolled GIF89a parser for per-frame timing.

MethodSummary
static humanBytes(int $bytes): stringRender a byte count the way the refusal messages promise: "64 MiB", not "67108864 bytes" (SA-D1, -053). Binary units, up to two decimals with trailing zeros trimmed.
static decode(string $path, int $cellsW, int $cellsH): arrayDecode a GIF file on disk into a list of Frames.
static decodeFile(string $path, int $cellsW, int $cellsH, bool $withCanvasRgba = false): DecodedAnimationThe canonical file decode as a single value (SA-G1 -006): frames, loop policy, and the walk's stop reason, captured where the truth lives instead of re-guessed by every consumer.
static readFile(string $path): stringRead a GIF file on disk into bytes for self::decodeBytes() and self::loopCount() — the ingress half of self::decode() exposed so a host can read once and feed both the frame stream and the loop-count inspection without a second open of the path.
static loopCount(string $bytes): ?intE-02: the NETSCAPE2.0 loop extension in GIF bytes, normalised to total playthroughs (mirror of libnsgif's app-extension intake, namzug16/libnsgif gif.c:808 and :862-871 — the block at 0x21 0xFF whose 11-byte identifier is "NETSCAPE2.0" or its Animation Shop twin "ANIMEXTS1.0", carrying the sub-block 0x03 0x01 &lt;lo&gt; &lt;hi&gt;).
static decodeBytes(string $bytes, int $cellsW, int $cellsH, bool $withCanvasRgba = false): \GeneratorDecode in-memory GIF bytes into a stream of Frames (E-07).

Frame final class

One downsampled GIF frame. Stored as a 2-D grid of RGB triples or null (transparent) in cell-coordinate space (post-downsample). The Renderer walks the grid and emits ANSI escapes per cell.

MethodSummary
static new(array $cells, int $delay = 10, int $disposal = self::DISPOSAL_NONE, bool $transparent = false, ?string $rgba = null, int $rgbaWidth = 0, int $rgbaHeight = 0): selfMint a frame through the geometry door (SA-V1 -021): the optional RGBA triple must AGREE. The bare constructor let any caller pair a buffer with mismatched (or zero) dimensions, after which hasRgba() answered true for a lying geometry and every byte-length consumer inherited the lie. Bytes without dimensions, or dimensions without bytes, are the same contradiction read from the other side — both refuse at construction, so nothing downstream re-validates.
hasRgba(): boolWhether this frame carries the full-canvas RGBA capture (E-07).
rgbaBytes(): stringThe composited frame as packed RGBA bytes — row-major, 4 bytes per pixel, rgbaWidth() × rgbaHeight() pixels. This is the chicle-parity frame representation: lossless pixels, so a consumer can size its own output at print time instead of inheriting this decoder's grid.
rgbaWidth(): int
rgbaHeight(): int
width(): int
height(): int

Lang final class

Per-library translation facade for sugar-animation.

Player final class

E-03: GIF player as a SugarCraft Model driven by an ABSOLUTE schedule. Loads every frame up-front (the decoder caps at 256); frame k is due at anchor + C[k] where C is the prefix sum of the frame periods (modulo one cycle of total length T), and each TickMsg re-arms the loop for the NEXT frame's deadline — max(nextDue - now, MIN_TICK_CS) — never a fresh copy of the CURRENT frame's delay. While the elapsed position resolves to a frame OTHER than the one on screen the table stays absolute from the kickoff origin: an overrun costs lateness, not drift, and the tick skips straight to its landing frame (the ArtLoop philosophy — on that path the displayed frame is a total function of elapsed time). The table DOES rescale at the wrap boundary, however: when the elapsed position lands back inside the window of the frame already on screen — which every stall of at least one full cycle does, as does a pump fired inside the current window — the tick force-advances exactly ONE frame and re-anchors the epoch to wall-clock now, so that frame holds a fresh full period. Post- wrap the cadence (the per-lap sequence of holds) is therefore preserved while the epoch is re-based, bounding the catch-up to one advance per tick. The naive alternative — continuing the absolute table without re- basing — was rejected because the force-advanced frame would survive only the sliver of window left before its table deadline (arbitrarily short partial holds at every stall boundary); the re-anchor is the shipped choice and PlayerScheduleTest pins the resulting index/arm stream against an independent walk. Before E-03 the Player re-armed the current frame's full delay on every tick, so the per-frame period was delay + handling + render time and playback silently stretched under load — the docblock here used to promise rate-stability the schedule did not deliver.

Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.

MethodSummary
__construct(public readonly array $frames, public readonly int $index = 0, public readonly bool $paused = false, public readonly string $preset = Renderer::PRESET_SOLID, public readonly ?Renderer $renderer = null, private readonly ?\Closure $now = null, public readonly ?float $fixedFps = null, public readonly ?float $maxSeconds = null, private readonly ?float $anchor = null, public readonly ?int $loops = null, private readonly int $lapsCarried = 0, private readonly ?\Closure $watch = null, private readonly float $elapsedCarried = 0.0, private readonly ?float $epochBasePos = null)The six seam parameters — $now, $anchor, $lapsCarried, $watch, $elapsedCarried, $epochBasePos — are internal wiring (test clock, schedule anchoring, lap carry across a reload, watch rebind, played-time carry across a re-anchor, the live epoch's establishment position), not caller vocabulary: hosts build Players via self::start() and the fluent setters, which thread the seams themselves. They stay public in the signature deliberately — promoted readonly state beats a parallel private-property ceremony — and the reload paths carry them via mutate().
init(): ?\Closure
update(Msg $msg): array
view(): string
withFixedFps(float $fps): selfE-09: override the per-frame GIF delays with a uniform cadence of $fps frames per second on the same absolute schedule. Immutable. Re-anchors the schedule to the currently shown frame so a mid-play switch never triggers an instant catch-up jump. Rates above self::MAX_FPS clamp to that advertised ceiling (chicle's CHICLE_ANIM_FPS_MAX): past the MIN_TICK_CS arm floor a faster request is indistinguishable from the ceiling, so the ceiling is made real rather than left a doc promise.
withMaxSeconds(float $seconds): selfE-09: stop playback once the schedule position (total play time; time spent paused never accrues) reaches $seconds. The bound makes the "total" literal: every re-anchor — pause/resume, manual step, the early-fire force-advance, a cadence swap — folds its played segment into the elapsed carry the check compares (playSeconds()), so the bound can no longer be laundered by interacting with it. The bound lives in the model and is checked on each tick — no wall-clock timer is armed for it, so a stalled loop cannot overshoot silently either.
withLoops(?int $plays): selfE-02: cap playback at $plays total playthroughs (null = forever, the default). The stop happens INSIDE the schedule — on the tick whose position crosses the final lap boundary the Player returns Cmd::quit() while still displaying the last shown frame — so no wall-clock timer is armed for the bound (same E-09 law as withMaxSeconds()): a stalled loop cannot overshoot silently.
playOnce(): selfE-02: play the frame stream exactly once and quit. This is the honest counterpart of libnsgif's remark that "the only way to play the animation once is not to have this extension at all" (namzug16/libnsgif gif.c:862-871): because an unauthored stream reports infinite from Decoder::loopCount(), a host that wants one pass must ask the Player for it, not read it off the bytes.
withWatch(\Closure $probe): selfE-10: attach a watch probe. The closure is re-run every WATCH_POLL_SECONDS (see the constant's docblock for the chicle parity and the disclosed deviations); null = "no change", a frame list = "reload onto it now". Returns a new Player — the seam is state, not mutation.
withFrames(array $frames): selfE-10: rebind the playback to a different frame stream IN PLACE — the reload half of the watch cycle, exposed publicly so hosts can swap frames without rebuilding the Player. The position restarts (index 0, carried laps 0, epoch unanchored so the first tick of the new stream anchors by the E-03 next-arrival law); playback policy — preset, renderer, cadence, duration bound, loop bound, and the watch seam itself — survives. A caller that wants the loop bound re-derived from the new bytes chains withLoops() onto the result. The asymmetry is the contract: the manual swap keeps the caller's bound because only the caller knows its intent, while the WatchMsg reload in self::update() re-derives the bound from the fresh bytes on purpose, so a file whose loop extension changed mid-session gets its new bound without the caller lifting a finger (pinned by PlayerWatchTest). The duration bound rides this survive-list as a carried total too — the live segment folds into the elapsed carry before the epoch drops, so swapping streams mid-run is not a budget reset either.
subscriptions(): ?\SugarCraft\Core\Subscriptions
playedSeconds(): ?floatE-09: the duration bound measured so far ON THE CURRENT SCHEDULE (null before the schedule is anchored, i.e. before the first tick) — the raw epoch position the E-03 cadence pins observe. The maxSeconds BOUND proper measures total play time across re-anchors — see self::playSeconds(); the carry applies to that bound, not this accessor.

Renderer final class

Render a Frame as ANSI-coloured cells.

MethodSummary
static withAdaptiveSize(int $reservedRows = 0): selfReturn a Renderer that adapts its output to fit the current TTY dimensions.
static new(): selfReturn a fresh Renderer with no adaptive sizing (default).
cols(): ?intThe column budget art and overlays are clipped to, or null when this renderer is unconstrained (the Player clamps its status overlay against exactly this budget — one source of truth per surface, so the overlay can never lie about the width the art got).
static render(Frame $f, string $preset = self::PRESET_SOLID): stringStatic-compatible render — delegates to a zero-sized (unconstrained) instance. Preserved for backward compatibility; new code should use self::new()->renderFrame().
renderFrame(Frame $f, string $preset = self::PRESET_SOLID): stringRender a frame. When adaptive dimensions are set (via withAdaptiveSize()), the output grid is clamped to fit within them.

TickMsg final class

Per-frame animation tick driving the sugar-animation image transition.

WatchMsg final class

E-10: One poll of the Player watch seam. Armed by the Player itself (init and every completed poll re-arm it at WATCH_POLL_SECONDS), consumed by Player::update() — the sugar-animation twin of chicle's run_watch re-stat cycle (tools/chafa/chafa.c:896-940), lifted from a g_usleep busy-loop into the event loop the TEA runtime already owns.

Configuration and options

OptionTypeDefaultEffect
cellsW, cellsHintnone (required)Cell grid for a decode. The grid is fixed for the animation's life.
Player::$pausedboolfalseStart paused. Space resumes.
Player::$presetstringRenderer::PRESET_SOLIDsolid or density. The d key toggles between them.
Player::$fixedFps?floatnullUniform cadence in frames per second, ignoring the GIF delays.
Player::$maxSeconds?floatnullStop after this many seconds.
Player::$loops?intnullStop after this many plays. playOnce() sets it to 1.
Renderer::withAdaptiveSize()int0 reserved rowsRows to keep free below the art when the terminal size is read.
ProgramOptions::__construct(), argument useAltScreenboolfalse in sugar-core; the examples pass trueRun in the alternate screen. Pass it as new ProgramOptions(useAltScreen: true). This is a sugar-core constructor argument, not a Player option.

The decode caps (Decoder::MAX_FRAMES, MAX_TOTAL_PIXELS, MAX_CELLS, MAX_INPUT_BYTES) are class constants, not options. Read them from the class rather than copying the numbers.

Keys and controls

The Player handles these keys. The keys are fixed. The library has no rebind API, so a host that needs different chords must intercept messages before they reach Player::update().

KeyAction
SpacePause or resume.
← / →Step back or forward one frame.
dToggle between the solid and density presets without losing your position.
q, Esc, Ctrl+CQuit.

Theme and styling

There is no theme object. Both presets always emit 24-bit truecolor SGR (38;2;… and 48;2;…). The library has no 256-color fallback and no NO_COLOR mode. On a terminal without truecolor the colors degrade, and density stays the more legible preset. The .ansi side has its own fallback: ArtLibrary resolves a slug through the tc, 256 and 16 depth cascade and picks a pre-authored variant. It does not recolor art at runtime.

Examples

examples/play.php builds a three-frame synthetic GIF in the system temp directory. The GIF has a red, green and blue band that slides across a black field. It decodes that GIF and plays it in the alternate screen. The temporary file is removed on shutdown.

php examples/play.php           # interactive player in a terminal
php examples/play.php < /dev/null   # prints: decoded 3 frame(s)

When stdout is not a terminal, the example prints a one-line summary and exits. Run it that way in CI or in a pipe.

Testing

The suite runs with PHPUnit 10 and the golden-render fixtures in tests/fixtures/:

composer install
vendor/bin/phpunit

The decoder tests use a set of hostile GIFs in tests/fixtures/bad/. They cover oversize descriptors, bad LZW data, zero-delay storms and frame floods. GoldenRenderTest compares the density render against tests/fixtures/density-3x3.golden. A changed render has to update that golden file on purpose.

Troubleshooting and FAQ

  • Decode throws a RuntimeException that names ext-gd. Install or enable the gd extension. The .ansi classes never need it.
  • The decode throws a cap error on a large GIF. The caps are Decoder::MAX_FRAMES (256), MAX_TOTAL_PIXELS (2,000,000), MAX_CELLS (100,000 per frame) and MAX_INPUT_BYTES (64 MiB). Shrink the source or lower the cell grid.
  • The art is clipped after a resize. This is by design. The cell grid is fixed at decode time. Decode again at the new size, or use the viewport-fit renderer, which clips rather than re-scales.
  • The status line wraps on a narrow terminal. The overlay is clamped to the renderer's column budget. It shows its full hint from 82 columns up. Use 82 or more columns for best results.
  • Colors look wrong, or the art shows raw escapes. The output is 24-bit truecolor. On a terminal without truecolor, the colors degrade. On TERM=dumb, expect raw escape sequences. Switch to the density preset with d for a shape that still reads without color.
  • The animation does not respect reduced-motion settings. The library does not read REDUCE_MOTION. Start paused with paused: true, slow it down with withFixedFps(), or bound it with playOnce().

Untrusted input

The parser is defensive but it is not a sandbox. Complete OSC sequences and unknown CSI bodies are dropped. Frame and AnsiArt keep only canonical SGR runs, so sgrText() never replays an escape the input carried. C0 control bytes outside an escape sequence stay in the output as glyph data. Echoing $cell->glyph raw, or sgrText(), passes them to the terminal. Bound file ingress with Decoder::MAX_INPUT_BYTES, which the file entry points enforce with a bounded read. At most MAX_INPUT_BYTES + 1 bytes are pulled, and a larger file is refused. fromString() and decodeBytes() take the bytes you hold and refuse input over the same MAX_INPUT_BYTES cap. That check runs once the bytes are already in memory, so bound the input size yourself before you read it.

Localization

Decode and parse errors, and the Player status overlay, go through Lang in the animation namespace. Translations ship for each locale in lang/. The literal key names the overlay advertises (space, d, q) do not change between locales.

Architecture

The GIF path runs Decoder (walk the stream and read each image) into CellSampler (area-average onto the grid) into Frame. The playback path runs Player (a TEA model that schedules TickMsg through Cmd::tick()) and Renderer (frame to SGR string). AnsiArt, ArtLibrary and ArtLoop form a separate path with no GD dependency.

Upstream mapping

Upstream ideaSugarAnimation classNotes
gifterm (Go): GIF to terminal cellsDecoder, CellSampler, RendererThe GIF decode and cell render are inspired by gifterm. The PHP code is native, not a port.
Charm TEA model (sugar-core)PlayerImplements Model with init(), update() and view().
Not upstream: .ansi art playbackAnsiArt, ArtLibrary, ArtLoopOriginal SugarCraft work.

Changelog and versioning

The package is published as sugarcraft/sugar-animation on Packagist and follows the monorepo's release flow. The repository has no separate changelog file. The commit history on GitHub records each change. The viewer that the package feeds is versioned separately as candy-gifview.

Source & demos

Demos

VHS-recorded GIF of the example shipped with the library. Regenerated by CI on pushes that touch the source.

Terminal recording of examples/play.php animating a synthetic GIF through both render presets

Play

Synthetic animated GIF from examples/play.php, decoded, played and toggled through both presets.
  • candy-gifview: the terminal viewer CLI built on this library.
  • SugarCore: the TEA runtime, Program, Cmd::tick() and the Model contract.
  • SugarImage: image rendering for terminals, for when you need more than a cell grid.