All 42 libraries

SugarAnimation

ANSI/GIF animation toolkit

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

SugarAnimation code coverage

Two animators in one package: it decodes a .gif from disk via ext-gd, downsamples each frame to a configurable cell grid, and paints it with 24-bit ANSI color — as full-cell background color (space glyphs) or as an ASCII luminance ramp — and it parses and replays truecolor .ansi art files frame by frame. The ready-made viewer CLI ships separately as candy-gifview.

Install

composer require sugarcraft/sugar-animation

Quickstart

# The ready-made 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
// Programmatic — "cat.gif" is just 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, 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 bundled examples/play.php generates a tiny synthetic animated GIF and plays it end-to-end — a self-contained way to see the pipeline without supplying any files of your own.

What's in the box

ext-gd decodeWalks the GIF byte stream for image-descriptor offsets, hands each frame to GD, area-average downsamples to cell space.
Area-average downsamplingHigher quality than nearest-neighbor — each cell averages the fully-opaque source pixels covering it; the palette path skips pixels matching 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 — the shape still reads where color is stripped.
Local color tablesPer-frame Local Color Table (LCT) extracted from the GIF Image Descriptor; falls back to the Global Color Table (GCT) when no LCT is present. Each frame is reassembled in GIF89a order — Graphic Control Extension, Image Descriptor, LCT, LZW data — so LCT frames decode with their own colors.
GCE transparency + disposalGraphic Control Extension (GCE) transparent-color index and disposal method (none/restore-bg/restore-prev) tracked per-frame in Frame.
Two presetssolid — full-cell 24-bit background color (space glyph). density — ASCII luminance ramp ' .:-=+*#%@' with a 24-bit foreground.
Pause + stepSpace pauses; ← / → step through frames manually.
Preset toggle + quitd swaps solid ↔ density without losing your position; q, Esc or Ctrl+C quits. The Player's keys are fixed — not rebindable.
Viewport-fit renderingRenderer::withAdaptiveSize() queries the TTY via SizeIoctl (ioctl TIOCGWINSZ) and clips the art to the viewport. The cell grid is fixed at decode, so a resize clips — art never re-scales; the Player's ~78-column status line is not width-clamped, so playback looks its best at 82+ columns.
.ansi art playbackTruecolor .ansi byte streams (SGR runs + glyphs, frame headers ESC[<n>A) parse into cell-grid frames via AnsiArt; ArtLibrary indexes a corpus and selects a slug at the deepest supported depth (tc → 256 → 16), and ArtLoop turns elapsed seconds into frame indices.
Bounded playbackplayOnce(), withLoops(n) and withMaxSeconds(s) cap a run; withFixedFps() pins advance to a uniform wall-clock cadence.
Decode capsOne decode holds at most 256 frames, 2,000,000 total source pixels, and 100,000 output cells, so a runaway file can't balloon the runtime. The caps bound decoding and compositing; the file entry points additionally refuse any file larger than Decoder::MAX_INPUT_BYTES (64 MiB) on the stat, before reading. decodeBytes() and AnsiArt::fromString() take bytes you already hold — their size is your budget.
Cmd::tick drivenCmd::tick($seconds, …) (sugar-core) schedules frame advance — no busy-waiting in the main fiber.

Untrusted .ansi input

The parser is defensive but not a sandbox. Complete OSC sequences and unknown CSI bodies are dropped, not rendered, and Frame/AnsiArt keep only canonical SGR runs, so sgrText() never replays an escape the input carried. Two caveats stand: C0 control bytes that are not part of an escape sequence are preserved as glyph data — echoing $cell->glyph raw (or sgrText()) hands them to your terminal, an audible-and-cursor hazard on hostile files — and file ingress is bounded by stat before reading (Decoder::MAX_INPUT_BYTES, 64 MiB) at AnsiArt::fromFile() and Decoder::readFile() — but fromString() parses whatever bytes you hand it, with no cap, so bound the corpora you point ArtLibrary and the string APIs at.

Reduced motion

No REDUCE_MOTION (or other reduce-motion convention) is consulted anywhere in the library — autoplay is autoplay. The real mitigations are API-side: construct the Player paused (new Player($frames, paused: true)) so nothing moves until Space, step manually with ←/→, slow the cadence with withFixedFps(), and bound the run with playOnce() / withMaxSeconds(). Consulting REDUCE_MOTION by default is a tracked code follow-up, not a current behavior.

Source & demos

API

ClassMethodDescription
Decoderdecode(path, cellsW, cellsH)Decode a GIF into a list of Frame objects — stretched to exactly cellsW×cellsH (no aspect-ratio fit); throws on cap breach, missing ext-gd, or non-GIF input.
DecoderdecodeBytes(bytes, cellsW, cellsH, withCanvasRgba)Decode from a byte string as a Generator; optionally carry full-canvas RGBA per frame.
DecoderreadFile(path) / loopCount(bytes)Read a file off disk / read the NETSCAPE loop count (null or 0 = infinite).
Frame__construct(cells, delay, disposal, transparent, rgba, …)Value object: one frame's cells, centisecond delay, disposal method, transparency, optional RGBA.
Player__construct(frames, index = 0, paused = false, preset = Renderer::PRESET_SOLID, renderer = null, fixedFps = null, maxSeconds = null, loops = null)Create the playback TEA model.
PlayerwithFixedFps(fps)Uniform cadence — positive finite; MAX_FPS (100,000) is a documented advisory ceiling the library does not enforce; hosts (candy-gifview) clamp.
PlayerwithMaxSeconds(s) / withLoops(n) / playOnce()Bound the run by time, repeat count, or a single pass.
PlayerwithFrames(frames) / withWatch(probe)Rebind the frame stream in place / install a reload probe closure.
AnsiArtfromFile(path) / fromString(bytes)Parse a .ansi byte stream into cell-grid frames.
AnsiArtframeCells(i) / sgrText(i) / width() / height() / frameCount() / isAnimated()One frame's AnsiCell grid / canonical SGR replay text / dimensions and frame metadata.
AnsiCellnew(glyph, sgr)One cell: glyph plus its canonical whole-state SGR (both public readonly).
ArtLibraryfromDir(dir) / pick(slug, depthTag) / randomSlug(depthTag) / mergeManifest(jsonl)Index a .ansi corpus; select a slug at the deepest supported depth (tc → 256 → 16).
ArtLoopnew(frameCount, frameSeconds, pauseSeconds) / frameAt(elapsed)Elapsed-seconds frame cycling for banners and logos.
Renderernew() / withAdaptiveSize()Unconstrained renderer / renderer that queries TTY size via SizeIoctl and clips output.
RendererrenderFrame(frame, preset)Render one frame to an ANSI string, clipped to its rows/cols.
Program (sugar-core)__construct(model, options)Create program.
Program (sugar-core)run()Start the event loop.
ProgramOptions (sugar-core)__construct(useAltScreen: true, …)Configure terminal mode.

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.