All 48 libraries

SugarVideo

Terminal video player

prior art: tplay · video-to-ascii mp4 gif webm webp avi ascii sixel kitty iterm2 subtitles ffmpeg ext-gd

SugarVideo code coverage

Terminal video player. It plays mp4, gif, avi, webm and animated webp on the fly, rendering each frame as ASCII, ANSI 256-color, truecolor half- or quarter-blocks, or through a graphics protocol (sixel, kitty or iTerm2), with WebVTT subtitle overlays. It builds on prior art in terminal video-to-text tools, including tplay (see Upstream mapping), and runs on the SugarCraft TEA runtime.

Install

composer require sugarcraft/sugar-video

Requires PHP 8.3+. GIF and animated WebP play in-process through ext-gd, with no ffmpeg needed. mp4, avi and webm need the ffmpeg and ffprobe binaries on $PATH. Those are a runtime toolchain, not a Composer package. Audio needs ffplay or mpv, and it is optional. Video decode through ffmpeg is refused on Windows, while GIF playback still works there.

Quickstart

php examples/play.php video.mp4           # play a video
php examples/play.php                    # synthetic test pattern (no file needed)
SUGAR_VIDEO_COLS=120 SUGAR_VIDEO_ROWS=40 php examples/play.php   # seed the size; the terminal's own size message overrides it (live resize always wins)
// Programmatic (mode auto-detects terminal capability):
use SugarCraft\Video\Player;
$player = Player::open('clip.mp4', cellsW: 80, cellsH: 24);   // mp4/avi/webm decode through ffmpeg
(new \SugarCraft\Core\Program($player))->run();

Concepts

Playback is a pipeline with four stages. A decoder turns the source into RgbFrame values. A renderer turns each frame into terminal output for the chosen mode. The Player is a TEA model that advances on ticks and returns its view. The Reel is the front door: you open a source, configure it with with*() methods, then call play(), or toPlayer() to get a paused Player you can embed.

The player starts paused. Nothing moves until you press Space, which is the reduced-motion default described under Accessibility. Timing comes from a monotonic clock, so an NTP step or a laptop resume does not fast-forward playback.

Tasks

Play a file with a chosen mode

use SugarCraft\Video\Reel;
use SugarCraft\Video\Render\Mode;

Reel::open('clip.mp4')
    ->withMode(Mode::HalfBlock)
    ->withSize(100, 30)
    ->withFps(24.0)          // null (the default) means auto-detect
    ->play();

Loop playback and attach subtitles

Reel::open('clip.mp4')
    ->withLoop(true)
    ->withSubtitles('clip.vtt')   // WebVTT, or lenient SRT
    ->play();

Play a signed remote stream

Reel::openUrl(
    'https://cdn.example.com/clip.mp4',
    ['Authorization' => 'Bearer ' . $token],   // forwarded to ffmpeg and to the audio companion
    ['cdn.example.com'],                          // host allowlist, the SSRF guard
)->play();

Credentials in the URL are redacted from every log line and error. A bare URL without an allowlist logs a warning and allows any host, so pin the allowlist for anything you do not control.

Embed the player in your own program

use SugarCraft\Video\Reel;

$player = Reel::open('clip.mp4')->withSize(80, 24)->toPlayer();   // paused, first frame ready
// $player is a TEA model: feed it ticks through your own Program loop and render view().

Decode frames without a terminal

The decoders run without any terminal, so they can be tested and used in batch code. examples/decode-frames.php generates a synthetic animation and reports each decoded frame.

use SugarCraft\Video\Decode\GifDecoder;
use SugarCraft\Video\Render\Mode;

$decoder = new GifDecoder();
$decoder->open('animation.gif', 40, 12, 10.0, Mode::HalfBlock);
while (($frame = $decoder->next()) !== null) {
    echo $frame->w, 'x', $frame->h, "\n";   // RgbFrame: packed RGB bytes plus dimensions
}
$decoder->close();

Styling and rendering modes

Rendering modes and the terminals they require.
ModeDescriptionTerminal requirement
asciiGrayscale luminance rampAny
ansi256256-color cube + grey ramp256-color
truecolor24-bit RGB truecolor24-bit color
halfblock24-bit ▀ half-blocks, 2x vertical resolution24-bit color
quarterblock24-bit quarter-block characters, 2x2 sub-cell resolution24-bit color
sixelSixel raster graphics protocol (DEC)Sixel-capable
kittyKitty graphics protocol (APC)Kitty-compatible
iterm2iTerm2 inline image (OSC 1337)iTerm2 / WezTerm
autoResolve the terminal from its environment (lookup table, no protocol negotiation), pick best available (the default)—

RendererFactory::supportedModes() lists the modes the current host can render, and RendererFactory::supports(Mode) answers for one mode. auto chooses from that list. truecolor is an explicit choice, and auto never selects it.

Luminance ramp

The ascii and ansi256 modes map brightness onto a character ramp. withRamp() selects minimal, standard or dense. LumaRamp::compute() derives BT.601 luma from RGB, and LumaRamp::char() maps a 0–255 value to a character.

Reel::open('clip.mp4')->withMode(Mode::Ascii)->withRamp('dense')->play();

Keys and keyboard controls

Keyboard controls for the bundled player program.
KeyAction
SpacePause / resume
←Seek backward 10 frames
→Seek forward 10 frames
[Decrease playback speed (-0.25x, min 0.25x)
]Increase playback speed (+0.25x, max 4.0x)
0-9Seek to 0-90% of video duration
mCycle to next rendering mode
q / Esc / Ctrl-CQuit

Behavior (no keyboard shortcut)

Behavior without a keyboard shortcut, configured at open time.
SettingBehavior
resizeTerminal resize (SIGWINCH) re-scales video automatically
loopLoop is set at open time via Reel::new()->withLoop(true)->play() (no keyboard shortcut)
subtitlesAttached at open time via Reel::withSubtitles() (no keyboard shortcut)
audioNo key toggles audio: Reel::withAudio() decides at open time; AudioPlayer::pause() / resume() (or mute() / unmute()) are the only levers

API reference

API surface: classes, constructors, and methods.
ClassMethodDescription
Reel::open(path)Open a video file
Reel::openUrl(url, headers, allowedHosts)Open a remote stream behind the SSRF guard
Reel::new()Create an unbound reel. play() falls back to the synthetic test pattern, but toPlayer() refuses to embed one
ReelwithMode(Mode)Set rendering mode
ReelwithSize(cols, rows)Set terminal cell dimensions
ReelwithFps(?float)FPS override (null = auto-detect)
ReelwithLoop(bool)Enable/disable loop
ReelwithRamp(name)Select the ascii/ansi256 luminance ramp (minimal, standard, dense)
ReelwithSubtitles(path)Attach a WebVTT (or lenient SRT) caption track
ReelwithHeaders(headers)Attach/replace request headers for remote sources
ReelwithAllowedHosts(hosts)Pin the remote host allowlist
ReelwithCellPx(w, h)Tell the player the terminal cell pixel size (graphics modes rasterize at cols·w × rows·h)
ReelwithAutoMode()Switch to auto mode: the renderer ladder picks the best supported mode at open time
ReeltoPlayer()Build the Player (paused; source already opened). ffmpeg-routed sources spawn their ffmpeg child now, local GIF and animated-WebP decode in-process, and the ffprobe child is transient
Reelplay()Run the player
Player::open(videoPath, cellsW, cellsH, ?fpsOverride, ?Mode, loop, ramp, cellPxW, cellPxH, subtitles, headers, frameBudgetMs, ?autoModeChooser)Open a video source; a null Mode auto-detects terminal capability (the default)
Player::fromDecoder(decoder, cellsW, cellsH, fps, mode, …)Mount playback over any injected Decoder (server-transcoded streams, test doubles)
Player::openForTest(decoder, fps, totalFrames, cellsW, cellsH, …)Deprecated alias of ::fromDecoder() for HalfBlock test wiring
Player::withSubtitles(WebVtt)Attach a parsed subtitle track to the player
Player::seekToSeconds(sec)Seek to a timeline position in seconds
Player::position() / ::duration()Current playhead and total duration in seconds
GifDecoderopen(source, cellsW, cellsH, fps, mode, startSec, headers) / next() / close()Pure-PHP GIF decoder. next() returns an RgbFrame or null at the end; loopCount() reads the NETSCAPE loop field
AnimatedWebpDecoderopen(...) / next() / frameDelaysMs() / loopCount() / isAnimated(path)Pure-PHP animated WebP decoder over a RIFF walk, with per-frame GD decode. supports() reports whether the host can decode WebP
FfmpegDecoderopen(...) / next() / fps() / exitCode() / buildCommand(...)Decodes through an ffmpeg child that pipes raw RGB frames. Refuses video on Windows with a guidance error
VideoSource::probe(path, hostRestricted) / ::unprobed(path) / ::fromFfprobeJson(path, json)Source description from ffprobe output. unprobed() defers the probe; fromFfprobeJson() parses a captured probe without running ffprobe
RendererFactorysupportedModes() / supports(Mode) / support(Mode, cols, rows) / diagnose()Which render modes this host can produce, and the probe report behind the answer
FfmpegCommandBuilderscrubbedEnv() / networkReconnectFlags() / headerInputFlags(headers) / inputSeekFlag(startSec)Builds the argv for ffmpeg and the audio companions.
WebVtt::parse(text) / cueAt(seconds)Parse a WebVTT (lenient SRT) track into cues; bounded at MAX_CUES. cueAt() finds the active caption for a playhead position
Synthetic::generate(path = DEFAULT_PATH, w = 120, h = 60, frames = 16, delayCs = 8)Write a looping rainbow-gradient test animation as one valid GIF89a stream. The returned path, not the argument, is the source of truth: a refused target yields a private stand-in path
AudioPlayer::start() / ::stop()Spawn and reap the audio child (ffplay/mpv) for the reel's source
AudioPlayer::pause() / ::resume()Signal the audio child to pause and resume
AudioPlayer::position() / ::hasStarted() / ::isPlaying()Child uptime in seconds, spawn state, and live-playback state
AudioPlayer::mute() / ::unmute() / ::isMuted() / ::exitCode()Mute toggle, mute state, and the child's exit code once reaped
HttpHeaders::none() / ::parse(headers)The empty header set, and validation of a name => value map (refusing list-shaped input and C0/DEL control bytes)
HttpHeaders::isEmpty() / ::pairs() / ::userAgent()Emptiness, validated name/value pairs, and the User-Agent override
HttpHeaders::toFfmpegHeaderString() / ::toMpvHeaderFields()Render the set into each player's CLI spelling
LumaRamp::char(luma, ramp)Map 0-255 luminance to character
LumaRamp::compute(r, g, b)Compute BT.601 luma from RGB

Only methods declared in sugar-video/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\Video

AudioPlayer class

Audio playback subprocess wrapper for video files.

MethodSummary
__construct(private readonly string $videoPath, private readonly ?int $startMs = null, private readonly ?\Closure $clock = null, array $headers = [], private bool $muted = false, private readonly bool $hostRestricted = false)
static setRestartIntervalForTesting(?float $seconds): void
static redactCredentials(string $source): stringStrip the userinfo segment — everything from scheme:// up to the LAST @ before the first path separator — from a source before it is interpolated into a log line.
start(): voidSpawn the audio subprocess (ffplay or mpv) if a suitable binary is available on this host.
stop(): voidStop the audio subprocess by terminating it in BOUNDED time.
hasStarted(): boolTrue once start() has been called (regardless of whether a binary was actually available). Lets the Player start audio on first play and resume() it on subsequent unpauses rather than re-spawning.
pause(): voidSuspend audio playback by terminating the subprocess.
resume(): voidResume audio playback from the tracked position.
position(): intThe audio position, in milliseconds, that a (re)spawn would start from — the original seek advanced by every pause's elapsed play time. Bare accessor per the library's no-get rule; exposed so pause/resume position tracking is observable and testable without a real audio device.
__destruct()E366's other measured half: a handle that simply goes out of scope does NOT wait for its child — PHP's resource destructor reaps an already-exited child and ABANDONS a live one, reparenting an ffplay to init with every inherited descriptor still open. stop() is idempotent, so an explicit call before teardown still wins; this is the backstop for the path where nobody remembered to.
mute(): voidM24: silence the companion — kills a live child and refuses future start()/resume() until unmute(). The video clock is unaffected.
unmute(): void
isMuted(): bool
isPlaying(): boolTrue when the audio subprocess is still running.
tick(): voidThe Player's per-frame heartbeat for the companion (SV-L87/087): the poll below promotes a restart deferred by the floor and records the alive-observation that bounds position billing (SV-L89/089). Cheap and idempotent — it spawns nothing outside a due promotion.
exitCode(): ?intReturn the exit status of the last OBSERVED termination.

Lang final class

Per-library translation facade for sugar-video.

Player final class

TEA Model for terminal video playback.

MethodSummary
static open(string $videoPath, int $cellsW, int $cellsH, ?float $fpsOverride = null, ?Mode $mode = null, bool $loop = false, string $ramp = 'standard', int $cellPxW = 10, int $cellPxH = 20, ?WebVtt $subtitles = null, array $headers = [], ?float $frameBudgetMs = null, ?\Closure $autoModeChooser = null, bool $hostRestricted = false): selfOpen a video file and return a Player ready for Program::run().
static fromDecoder(Decoder $decoder, int $cellsW = 80, int $cellsH = 24, float $fps = 24.0, Mode $mode = Mode::HalfBlock, int $totalFrames = 0, string $videoPath = '', bool $loop = false, string $ramp = 'standard', ?\Closure $audioFactory = null, ?AudioPlayer $audioPlayer = null, bool $paused = true, int $cellPxW = 10, int $cellPxH = 20, ?WebVtt $subtitles = null, array $headers = [], float $frameBudgetMs = 0.0, ?\Closure $clock = null): selfThe blessed public seam for driving a Player from any Decoder implementation.
static openForTest(Decoder $decoder, float $fps, int $totalFrames = 0, int $cellsW = 80, int $cellsH = 24, string $videoPath = '/fake', bool $loop = false, string $ramp = 'standard', ?\Closure $audioFactory = null, ?AudioPlayer $audioPlayer = null, bool $paused = true, int $cellPxW = 10, int $cellPxH = 20, ?WebVtt $subtitles = null, ?\Closure $clock = null): selfFactory for tests: create a Player with an injected decoder.
init(): ?\Closure
update(Msg $msg): array
static clampCells(int $cols, int $rows): arraySV-H7/007: clamp a cell geometry into the documented pane window — cols in [MIN_COLS, MAX_COLS], rows in [MIN_ROWS, MAX_ROWS]. Every entry that accepts a host-supplied size (open, fromDecoder, updateResize, Reel::withSize) routes through here so the window is single-sourced: the frame block view() builds is cellsH lines x cellsW columns, and an unclamped pane is a multi-megabyte string per frame — a memory DoS at one constructor call, not a rendering curiosity.
view(): stringRender the current frame to a full ANSI string.
static setGeometryAssertsForTesting(?bool $on): void
static areaAverageRgb(string $bytes, int $w, int $byteLen, int $x0, int $y0, int $x1, int $y1): arrayInclusive-box channel mean over the raw rgb24 grid (M21).
withAudio(bool $on): selfM24: opt audio in or out (the 'm' key stays the mode cycle by design).
withSeek(int $targetIndex): selfSeek to a specific frame index. SV-H11/011: a factory-owned decoder is re-spawned at the target's SECONDS (fast -ss / cursor jump — one pull lands there); an in-place decoder closes-and-reopens at its head and decodes forward, bounded by the frame budget. The landed index is always the truth the new state records (SV-H4/013).
position(): floatCurrent playback position in content seconds (videoTime).
headers(): arrayThe HTTP request headers this player re-presents on every decoder rebuild (empty for a local file). Bare accessor per the library's no-get rule.
rendersWholeScreen(): boolWhether view() ships the pane as ONE indivisible paint — the mosaic/image rungs emit a raster blob whose bytes carry no line structure, so a host that line-diffs its output must repaint whole frames instead (SV-M34/034). Every text rung — including the direct Ansi256 row stream, whose rows carry their own SGR and split cleanly at \r\n — answers false: its frames are row-addressable.
duration(): floatTotal duration in content seconds, or 0.0 when unknown (a stream of indeterminate length, where totalFrames is 0).
canSeekByTime(): boolAsk whether time-seeking is supported HERE before doing it and taking a runtime throw (SV-M25/025 — candy-top's frame RPC is the motivating caller: it wants a yes/no, not an exception class to catch).
seekToSeconds(float $sec): selfSeek to an absolute time in content seconds (clamped to [0, duration]).
frameAt(float $sec): ?RgbFrameGrab a single frame at $sec for a scrubber-hover thumbnail.
stop(): voidTear down playback: stop the audio companion and close the decoder (terminating its ffmpeg subprocess). Idempotent — safe to call more than once. A host screen calls this when leaving the player so no audio/video subprocess leaks across play → back.
isStopped(): boolWhether stop() has torn this player down (M15).
pause(): selfPause playback. Returns a new Player with paused=true.
play(): selfResume playback. Returns a new Player with paused=false and re-anchored clock so play-time accumulates correctly.
withSubtitles(WebVtt $track): selfAttach a parsed subtitle track to the player.
subscriptions(): ?\SugarCraft\Core\Subscriptions
teardownCmd(): ?\ClosureThe Cmd a host runs before stop() when it tears the player down outside update(). stop() is void, so this is the only way to hand the runtime the delete for the last Kitty frame; without it the frame outlives the player. Null when nothing was drawn or the current mode cannot delete by id.

Reel final class

Terminal video player facade — plays a video file by decoding frames on the fly and rendering them to ASCII / ANSI / truecolor half-block / sixel / kitty output, the way mpv -vo tct, tplay, video-to-ascii, and glyph do.

MethodSummary
static setProgramRunForTesting(?\Closure $run): void
static new(): selfConstruct an empty player with no source bound yet.
static open(string $path): selfOpen a video source by path. Does not probe or decode — it only records the path so the instance can be configured before playback.
static openUrl(string $url, array $headers = [], ?array $allowedHosts = null): selfOpen a remote video source by http(s) URL.
static preview(string $path): selfA glance-sized, silent Ansi256 preview (SV-L64/064).
static captioned(string $path, string $subtitlePath): selfA clip paired with its caption track (SV-L64/064).
static ambient(string $path): selfA silent looping wall piece (SV-L64/064).
path(): stringThe source video path this player was opened with ('' when unbound).
mode(): ?ModeThe configured rendering mode (null means auto-detect).
cols(): intThe configured terminal cell width.
rows(): intThe configured terminal cell height.
fps(): ?floatThe configured FPS override, or null for auto-detect from probe.
loop(): boolWhether playback loops back to the start at end-of-stream.
ramp(): stringThe configured luminance ramp name ('minimal', 'standard', 'dense').
allowedHosts(): ?arrayThe configured remote-host allowlist, or null when host restriction is disabled (any host is accepted — SSRF surface; see openUrl()).
headers(): arrayThe configured HTTP request headers for a remote source (empty otherwise).
cellPx(): ?arrayThe caller-supplied pixel size of one terminal cell, as [width, height], or null when none was set.
withMode(Mode $mode): selfSet the rendering mode. Returns a new Reel (immutable).
withAutoMode(): selfSet the rendering mode to auto-detect (probed at play time). Returns a new Reel (immutable).
withLoop(bool $loop = true): selfEnable (or disable) looping: replay from the start at end-of-stream instead of stopping. Returns a new Reel (immutable).
withRamp(string $name): selfSet the luminance ramp. Returns a new Reel (immutable).
withoutRamp(): selfReturn to the default luminance ramp (SV-L50).
withSize(int $cols, int $rows): selfSet the terminal size in cells. Returns a new Reel (immutable).
withFps(?float $fps): selfSet a target FPS override. Pass null to use auto-detect from video probe. Returns a new Reel (immutable).
withFrameBudget(float $ms): selfSet the per-tick decode budget (milliseconds) threaded to the built Player (SV-M19). Returns a new Reel (immutable).
withSubtitles(string $path): selfAttach a subtitle file (WebVTT or SRT) to the player.
withoutSubtitles(): selfDetach the subtitle track (SV-L50).
withAudio(bool $on): selfM24: opt out of the audio companion for this Reel ('m' stays the mode key).
withAllowedHosts(array $hosts): selfRestrict remote (http(s)) playback to a set of trusted hosts.
withHeaders(array $headers): selfSet the HTTP request headers presented to a remote (http(s)) source.
withoutHeaders(): selfClear every request header (SV-L50). Returns a new Reel (immutable).
withCellPx(int $w, int $h): selfTell the player the real pixel size of one terminal cell.
toPlayer(): PlayerBuild the playback Model from the configured options WITHOUT running it.
play(): voidRun the player: creates a Player from the configured options and executes the TEA program loop via Program::run().

Sync final class

Wall-clock frame pacing and skip/hold decisions for video playback.

MethodSummary
static targetFrame(float $videoTimeSeconds, float $fps): intCompute the target frame number from video content time.
static shouldSkip(int $currentFrame, int $targetFrame): boolDetermine whether we are too far behind and must skip frames.
static shouldHold(int $currentFrame, int $targetFrame): boolDetermine whether we are ahead and must hold/delay frames.

Synthetic final class

Synthetic animated test-pattern generator.

MethodSummary
static defaultPath(): stringDefault on-disk path for the generated demo GIF: the host's temp directory.
static generate(?string $path = null, int $w = 120, int $h = 60, int $frames = 16, int $delayCs = 8): stringGenerate an animated rainbow-gradient GIF and return its path.

SugarCraft\Video\Decode

AnimatedWebpDecoder final class

Animated WebP decoder — pure PHP + GD, no subprocess.

MethodSummary
__construct(int $cellPxW = 10, int $cellPxH = 20)
static supports(): boolWhether this PHP's GD can decode WebP at all — the capability gate that replaces the ffmpeg-presence probe of the original design. Public so consumers (and the factory's callers) can answer "is animated WebP playable here?" without opening a decoder.
static setWebpCapableForTesting(?bool $capable): void
static setCompositeTouchBudgetForTesting(?int $budget): voidTest seam for the composite-time budget (same shape as the capability mock above): a scripted ceiling lets the refuse arm be pinned without shipping a 20M-pixel fixture through the suite. Null restores the class ceiling.
static isAnimated(string $path): boolCheap container sniff: does this file claim WebP animation?
open(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, array $headers = []): void
next(): ?RgbFrame
frameDelaysMs(): arrayPer-frame display durations in milliseconds, container order.
loopCount(): ?intTotal playthroughs the author requested — the SAME contract GifDecoder ships (review 015): null when the file says "forever", N + 1 when the container carries raw repeats N (one initial pass plus N repeats). The unmapped container field stays available via rawLoopField() for diagnostics.
rawLoopField(): intThe raw libwebp loop field, verbatim: 0 = forever, N = N repeats.
getIterator(): \Generator
close(): void
reopen(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, array $headers = []): void
reopensInPlace(): boolA fresh open() re-reads (and re-composites) the file, so a seek/resize rebuild is a plain close()+open() — same answer FfmpegDecoder gives.
seeksBySeconds(): boolSV-M25/025: true — open() consumes $startSec as a container-truth skip (cumulative frame durations, exact), so the Player's seconds routes land on it through the close()+open() rebuild.
static setStillDecodeForTesting(?callable $decode): voidTest seam (same shape as the capability mock): scripted GD behaviour for decoding one ANMF still, so the build-variance fallback arm can be pinned on a host whose libwebp does not exhibit it. Null restores the live decode.

Decoder interface

Interface for video decoders that produce RgbFrame objects.

MethodSummary
open(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, array $headers = []): voidOpen the decoder for a source file, targeting a grid of cellsW x cellsH at approximately the given fps.
getIterator(): \GeneratorYield the next RgbFrame, or null if there are no more frames.
next(): ?RgbFrameReturn the next RgbFrame, or null if no more frames are available.
close(): voidClose resources (pipes, processes) held by the decoder.
reopen(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, array $headers = []): voidRe-open the decoder for a source file at the given grid size and fps.
reopensInPlace(): boolWhether reopen() is a faithful in-place rebuild of this decoder.
seeksBySeconds(): boolWhether a start-SECOND argument actually lands the playhead.

DecoderFactory final class

Factory for creating the appropriate Decoder based on the source file.

MethodSummary
static new(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, int $cellPxW = 10, int $cellPxH = 20, array $headers = [], bool $hostRestricted = false): DecoderCreate an appropriate decoder for the given source file.
static isLocalAnimatedWebp(string $source): boolTrue when $source names an existing LOCAL file with a .webp suffix (case-insensitive) whose container claims animation.

FfmpegDecodeFailure final class

The ffmpeg child died abnormally while frames were expected.

FfmpegDecoder final class

Ffmpeg-based video decoder using proc_open.

MethodSummary
__construct(private readonly int $cellPxW = 10, private readonly int $cellPxH = 20, private readonly bool $hostRestricted = false)
open(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, array $headers = []): void
static buildCommand(string $ffmpegPath, string $source, int $frameW, int $frameH, float $fps, float $startSec = 0.0, bool $graphics = false, ?int $padW = null, ?int $padH = null, ?HttpHeaders $headers = null, bool $hostRestricted = false): arrayAssemble the ffmpeg argv as an array (never a shell string — proc_open passes the args verbatim with no shell, so nothing needs escaping).
static isNetworkSource(string $source): boolWhether the source is an http(s) URL (vs a local file path). ffmpeg's reconnect options apply only to the network protocols.
next(): ?RgbFrame
getIterator(): \Generator
close(): void
static setWindowsHostForTesting(?bool $isWindows): void
exitCode(): ?intReturns the exit status of the last ffmpeg process once a termination has been OBSERVED — the close() reap or, earlier, the not-running sighting in refuseAbnormalExit() (SV-L49/049); null before either, or while the child is still running.
reopen(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, array $headers = []): void
reopensInPlace(): boolAn ffmpeg decoder is NOT reopened in place: every geometry/mode change rebuilds the scale filtergraph and (for a seek) the -ss input position, so the honest rebuild is close()+a fresh DecoderFactory build. Player only consults this to decide whether it may keep the instance; here it says no, so Player rebuilds via the factory using the source path — which an ffmpeg-backed Player always has.
seeksBySeconds(): boolSV-M25/025: true — the rebuild route spawns ffmpeg with -ss BEFORE -i, so a start-second argument lands natively (the keyframe-snap trade-off is documented on Player::seekToSeconds(), not hidden here).
fps(): floatReturn the cached fps value from the last open() call.
__destruct()E366 backstop: a decoder that merely goes out of scope does not wait for its child — PHP's resource destructor abandons a RUNNING one to init with every inherited descriptor. close() is idempotent, so an explicit call before teardown still wins; this covers the path where nobody remembered to make one.

GifDecoder final class

Decoder implementation that wraps sugar-animation's pure-PHP GIF decoder.

MethodSummary
__construct(private readonly int $cellPxW = 10, private readonly int $cellPxH = 20)
open(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, array $headers = []): void
static textSampled(): ?stringm14: non-null hint when the graphics path will silently degrade because this PHP has no image extension; null on a normal GD-capable host.
next(): ?RgbFrame
conversionCount(): intConversions this decoder has actually performed (M40).
emitCacheBytes(): intResident bytes currently held by the converted-frame cache (M40).
static setEmitCacheCeilingForTesting(?int $bytes): voidTest seam for the emit-cache byte ceiling; null restores MAX_EMIT_CACHE_BYTES. The ceiling is eviction policy, and policy is only honest if its trip point is unit-testable without shipping a 23 MiB fixture — the project's budget-seam idiom.
loopCount(): ?intThe playthrough count authored into the GIF's NETSCAPE2.0 loop extension, normalised by sugar-animation's AnimationDecoder::loopCount() — null means infinite (no extension present, or the raw-0 "loop forever" value; libnsgif's gif.c:862-871 reading), an integer N >= 2 means N total plays (raw values spell EXTRA repeats, so a total of 1 is not reachable from authored bytes — see playOnce()). null also answers before any open(); after close() it keeps reporting the last audited capture, because $bytes outlives close() by design.
playOnce(): boolTrue only when the bytes explicitly author exactly one playthrough. Unreachable from a valid NETSCAPE extension (raw 0 = forever, raw N > 0 = N+1 totals, so 1 is never produced — libnsgif documents "the only way to play the animation once is not to have this extension at all", gif.c:862-871, and the chicle CLI never consumes the loop field at all, it plays forever); this is the honest answer a host needs to know the difference between "the author said once" (some day, some other container) and "unauthored, play forever by policy".
static isGifFile(string $path): boolWhether $path names an existing file whose first six bytes are the GIF87a/GIF89a signature — container magic, not file extension.
getIterator(): \Generator
close(): void
reopen(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, array $headers = []): void
reopensInPlace(): boolFalse — a seek cannot WALK this decoder's live cursor in place the way an injected double replays from its head; positions are taken by re-hydrating (the seconds route or the index walk both re-open from the captured bytes and land the cursor).
seeksBySeconds(): boolSV-M25/025: true — reopen() honours $startSec as a cursor jump over the open-time capture (the M38 single-capture law), so the Player's seconds routes land on it without any re-read.

RgbFrame final readonly class

A readonly value object holding one decoded video frame.

MethodSummary
__construct(public string $bytes, public int $w, public int $h, public ?string $png = null)
toGd(): \GdImageConvert the frame to a GD image.

SugarCraft\Video\Msg

ResizeRebuildMsg final class

Deferred apply of a pending terminal resize .

MethodSummary
static instance(): selfReturn the singleton ResizeRebuildMsg instance.

TickMsg final class

Per-frame tick driving the video player.

MethodSummary
static instance(): selfReturn the singleton TickMsg instance.

SugarCraft\Video\Render

AsciiRenderer final class

A-11: ASCII / ANSI renderer — thin bridge over sugar-image's canonical AsciiRenderer.

MethodSummary
__construct(private readonly string $ramp = 'standard')
static colorModeFor(Mode $mode): AsciiColorModeA-06 accessor route: the video Mode enum projects onto the canonical colour-depth enum. Graphics modes never reach this renderer (the factory routes them elsewhere), so they default to Mono — mirroring the legacy match's default arm, which emitted plain characters for them too.
render(RgbFrame $frame, Mode $mode): string
cellDimensions(Mode $mode): array

AutoMode final class

Marker value for "auto-detect the best rendering mode".

MethodSummary
static new(): selfThe marker instance — the only way to obtain one.

Color final class

Color utility for packing RGB components into a single integer.

MethodSummary
static pack(int $r, int $g, int $b): intPack RGB components into a 0xRRGGBB integer.

FrameRenderer interface

Contract for rendering an RgbFrame to an ANSI escape-string.

MethodSummary
render(RgbFrame $frame, Mode $mode): stringRender one RgbFrame to an ANSI string at the frame's native dimensions.
cellDimensions(Mode $mode): arrayThe terminal cell dimensions a pixel of the GIVEN mode consumes.

GraphicsRenderer final class

Graphics renderer — emits Sixel / Kitty / iTerm2 protocol output.

MethodSummary
__construct(private readonly Mode $mode, private readonly int $cellPxW = 10, private readonly int $cellPxH = 20)
render(RgbFrame $frame, Mode $mode): string
retirement(): stringThe deletes that retire this renderer's Kitty frames: the escape bytes a Player writes as a Cmd when it replaces the renderer, so no frame outlives the session in the terminal's image store. '' when nothing was drawn or the backend cannot delete by id.
cellDimensions(Mode $mode): array

HalfBlockRenderer final class

Half-block Unicode renderer — delegates to sugar-image's HalfBlockRenderer.

MethodSummary
render(RgbFrame $frame, Mode $mode): string
cellDimensions(Mode $mode): array

LumaRamp final class

256-entry luminance-to-character lookup table.

MethodSummary
static ramp(string $name = self::DEFAULT_RAMP): arrayReturn the 256-entry character array for the named ramp.
static isValidRamp(string $name): boolReturn true if the named ramp is a valid known ramp.
static char(float $luma, string $ramp = 'standard'): stringReturn the character for a given 0-255 luminance value.
static compute(int $r, int $g, int $b): intCompute BT.601 (SMPTE-C) luminance from RGB components.

Mode enum

Rendering mode for terminal video output.

Cases: Ascii · Ansi256 · TrueColor · HalfBlock · QuarterBlock · Sixel · Kitty · Iterm2

PHP also provides cases(), from() and tryFrom().

MethodSummary
wireName(): stringThe exact wire token this mode accepts (SV-M36).
static wires(): arrayThe complete accepted-token list: auto first, then every case token. The CLI validates against this single source (SV-M36), so no hand-written token list can drift from the enum.
rowsPerCell(): intSource pixel-rows consumed per terminal cell. Half/quarter-block pack 2; graphics modes resolve in the renderer (treated as 1 here).
colsPerCell(): intSource pixel-cols per terminal cell. Quarter-block packs 2 across.
isGraphics(): boolWhether this is a pixel-graphics protocol (Sixel/Kitty/iTerm2) rather than a text/cell mode. Graphics modes decode at the terminal's full pixel resolution (cells × cell-pixel-size) and emit a real image, so the decoder sizes their frames from the cell pixel geometry — not the 1-/2-rows-per-cell packing the block modes use.
label(): stringHuman-readable description of the rendering mode.

QuarterBlockRenderer final class

Quarter-block Unicode renderer — delegates to sugar-image's QuarterBlockRenderer.

MethodSummary
render(RgbFrame $frame, Mode $mode): string
cellDimensions(Mode $mode): array

RendererFactory final class

Static factory for FrameRenderer instances.

MethodSummary
static diagnose(): ProbeReportThe terminal's capability report — probed once, memoized thereafter.
static withKittyConfirmation(ProbeReport $report, bool $confirmed): ProbeReportThe pure half of diagnose(): an unconfirmed Kitty claim is removed from the report; every other capability and the detection time are carried over unchanged (resolved facts in, report out, no probing).
static setKittyGateForTesting(?\Closure $gate): voidP1-13b test seam: script the Kitty APC confirmation (null = the live probe). Lets pins drive the TERM-only claim without a tty.
static setDiagnoseForTesting(?ProbeReport $report): voidTest seam: seed the capability memo (null = clear it).
static setGraphicsGateForTesting(?\Closure $gate): voidSV-L66/066: seam for the graphics rung's ext-gd requirement (null = the live function_exists check). new() consults it through graphicsRenderable(), so a pin can script a gd-less PHP build — the honest test target is the caller's DEGRADE/THROW split, which is otherwise unreachable on every real host.
static graphicsRenderable(): boolWhether this PHP build can paint the GD-backed rungs. The single door is consulted by the graphics construction gate in new() (encode paths) and — since SV-L72/072 — by the block-bridge entry guards in HalfBlock/QuarterBlockRenderer, which cross RgbFrame through GD at render time while their construction leg stays gd-free for the Player.
static supportedModes(): arrayEvery Mode this terminal can honestly render right now.
static supports(Mode $mode): boolWhether this terminal can actually RECEIVE the mode's output.
static support(Mode $mode, ?int $cols = null, ?int $rows = null): SupportThe FULL honest verdict for one mode at one geometry (SV-M35/035).
static supportShape(Mode $mode, bool $claimsProtocol, bool $gdPresent, bool $blockGlyphsSafe, ?int $cols = null, ?int $rows = null): SupportThe pure decision behind support() — resolved facts in, verdict out, no probing (the autoModeFrom() pattern: pins drive every arm without poisoning the process environment).
static canRender(Mode $mode, int $cols, int $rows): boolThe boolean the consumer loop wants: would support() say Supported at this exact seat+size? (SV-M35/035 — candy-code can delete its hand-rolled graphics-mode matrix on top of this door.)
static autoMode(): ModeReturn the best Mode enum case for the current terminal.
static autoModeFrom(bool $sixel, bool $kitty, bool $iterm2, ?ColorProfile $profile, TermInfo $info): ModeThe pure decision behind autoMode() — resolved inputs in, Mode out, no probing. autoMode() collects the live signals (capability report, color profile, and the PURE TermDb table consult — no tty, no exec, matching the ladder's own "no invented detection" rule); tests drive this seam directly instead of poisoning the process environment.
static auto(?Mode $preferred = null): FrameRendererPick the best renderer by probing terminal capabilities.
static new(Mode $mode, string $ramp = 'standard', int $cellPxW = 10, int $cellPxH = 20): FrameRendererReturn the renderer for the given explicit mode.

Support enum

The one-question answer for "can this terminal render this mode here?".

Cases: Supported · NeedsProtocol · NeedsGd · NeedsBlockGlyphs · GeometryTooSmall · GeometryTooLarge

PHP also provides cases(), from() and tryFrom().

MethodSummary
isRenderable(): bool
notice(array $params = []): stringThe refusal in one sentence (localised; the branded diagnostic voice).

SugarCraft\Video\Source

HttpHeaders final class

Immutable, already-validated HTTP request headers for a remote video source.

MethodSummary
static none(): selfThe empty set — no headers supplied, nothing to emit.
static parse(array $headers): selfValidate raw caller-supplied headers into a trusted instance.
isEmpty(): boolTrue when there is nothing to add to the request.
pairs(): arrayThe validated pairs, in submission order.
userAgent(): ?stringThe User-Agent value to pass as ffmpeg's -user_agent, or null when none was given.
toFfmpegHeaderString(): ?stringThe value for ffmpeg's -headers option: every header except User-Agent, each terminated by CRLF exactly as it will appear on the wire.
toMpvHeaderFields(): arrayThe values for mpv's repeatable --http-header-fields option (one bare Name: value per occurrence; mpv adds its own line terminators).

Probe class

Probes the host environment for FFmpeg toolchain binaries.

MethodSummary
static setClockForTesting(?\Closure $clock): voidInject a deterministic clock (seconds since arbitrary origin) for the memo-expiry tests; null restores the live monotonic hrtime clock.
static ffmpeg(): ?stringPath to the ffmpeg binary, or null if not found.
static ffprobe(): ?stringPath to the ffprobe binary, or null if not found.
static ffplay(): ?stringPath to the ffplay binary, or null if not found.
static mpv(): ?stringPath to the mpv binary, or null if not found.
static hasFFmpeg(): boolTrue when the ffmpeg binary is available on this host.
static clearBinaryCacheForTesting(): voidDrop every memoized lookup. For production callers the TTL converges on its own; this exists for tests that rewrite PATH (the HidesPathBinaries/StubbedPathBinaries concerns) and for any host that wants an immediate re-probe after mutating PATH itself.

VideoSource final class

Immutable value object describing a video source probed from ffprobe JSON output.

MethodSummary
__construct(public readonly string $path, public readonly int $width, public readonly int $height, public readonly float $duration, public readonly float $fps, public readonly bool $hasAudio)
static unprobed(string $path): selfThe metadata-free VO: everything a probe would answer stays unknown (zero dimensions, zero duration/fps, no audio). SV-M39/039 — a caller who pins fps themselves is declaring they know the stream, and fps is the ONLY probe product Player::open() still needs then, so the ffprobe child is skipped wholesale rather than consulted and ignored. Distinct from a FAILED probe's empty default because it is a choice, not a degradation: no child was ever spawned.
static fromFfprobeJson(string $path, string $json): selfConstruct a VideoSource from a path and raw ffprobe JSON output.
static probe(string $path, bool $hostRestricted = false): selfProbe a video file using ffprobe and return a VideoSource.

SugarCraft\Video\Subtitle

Cue final class

A single subtitle cue — the text shown between $start and $end (seconds). Immutable.

MethodSummary
__construct(public readonly float $start, public readonly float $end, public readonly string $text)
contains(float $seconds): boolWhether $seconds falls within [start, end) — i.e. this cue is showing.

WebVtt final class

A parsed WebVTT subtitle track — a time-sorted list of Cues with a cueAt() lookup for the caption showing at a given playback time: two binary searches — rightmost start at or before the position, and the leftmost cue whose (prefix-maximum) end reaches it — so cues that provably cannot contain the position are never even looked at (SV-VTT/084). The walk that remains is bounded by real overlap, not by caption-free gaps, and the look runs on EVERY painted frame.

MethodSummary
cues(): array
isEmpty(): bool
static parse(string $text): selfParse WebVTT (or SRT) text into a track.
cueAt(float $seconds): ?stringThe caption text showing at $seconds, or null when nothing is.
static sanitizeForTerminal(string $text): stringThe terminal-safety half of cleanText() on already tag-stripped text: newline/tab collapse, escape-sequence and zone-sentinel sweep, C0/DEL/C1 removal, and UTF-8 repair. Idempotent — running it over its own output changes nothing.

SugarCraft\Video\Support

FfmpegCommandBuilder final class

Shared argv assembly for every ffmpeg-family child sugar-video spawns.

MethodSummary
static scrubbedEnv(): arrayEnvironment for every media child: the parent env MINUS anything a spawned ffmpeg/ffplay/mpv/ffprobe must not honor.
static isNetworkSource(string $source): boolWhether the source is an http(s) URL (vs a local file path).
static networkReconnectFlags(bool $hostRestricted = false): arrayThe http/https protocol reconnect block, as input options (so BEFORE -i).
static headerInputFlags(HttpHeaders $headers): arrayThe header input options for the ffmpeg/ffplay dialect: one -headers blob (every field except User-Agent, CRLF-terminated exactly as it hits the wire) plus a dedicated -user_agent.
static mpvHeaderFieldFlags(HttpHeaders $headers): arrayThe header options for the mpv dialect: one repeatable --http-header-fields=Name: value per field.
static inputSeekFlag(float $startSec): arrayFast input seek (-ss BEFORE -i) as ffmpeg-family argv: decodes from the keyframe at/just before $startSec without walking the whole file, which is what makes scrubbing a multi-GB network stream instant.
static formatFloat(float $value): stringA float formatted for ffmpeg filter argv, locale-immune.
static secondsFromMillis(int $ms): stringMilliseconds as a fixed S.mmm seconds string built from integer math.
static ffplayAudioCommand(string $binary, string $source, int $seekMs, HttpHeaders $headers, bool $hostRestricted = false): arrayThe ffplay audio-only command: -nodisp -autoexit, an optional input seek, the signed-stream headers, then the source as the bare input.
static mpvAudioCommand(string $binary, string $source, int $seekMs, HttpHeaders $headers, bool $hostRestricted = false): arrayThe mpv audio-only command: --no-video --really-quiet, an optional --start=, then the header fields and the source.

Demos.

VHS-recorded GIFs of every example shipped with the app. Regenerated automatically on every push that touches the source.

VHS recording of the play example: a synthetic rainbow-gradient test pattern scrolling through the terminal renderer in real time

Play

Synthetic rainbow-gradient GIF used by the playback demos.

The recorded demos animate at full terminal speed and loop automatically. Flashing content can affect photosensitive viewers (WCAG 2.3.1 / 2.3.3); the player ships no static-fallback toggle today, so treat these GIFs as motion warnings.

Configuration

Reel options

Options set on a Reel before play() or toPlayer().
OptionTypeEffect
withMode()ModeRendering mode. The default resolves the mode from the terminal environment (auto).
withSize()int, intCell width and height. The terminal's own size message overrides it.
withFps()?floatFrame rate override. null auto-detects it.
withLoop()boolLoop from end back to start.
withRamp()stringLuminance ramp for ascii and ansi256: minimal, standard or dense.
withSubtitles()string (path)WebVTT or lenient SRT caption track.
withHeaders()arrayRequest headers for remote sources, validated by HttpHeaders.
withAllowedHosts()arrayHost allowlist for remote sources. Pin it in production.
withCellPx()int, intTerminal cell pixel size, used by the graphics modes.
withFrameBudget()float (ms)Time spent on catch-up decoding per tick. 0.0 removes the budget. Player::open() arms max(50 ms, 2 × frame interval) when none is set.
withAudio()boolStarts the audio companion (ffplay or mpv) with the video.

Environment variables

Environment variables read by sugar-video.
VariableRead byEffect
SUGAR_VIDEO_DEBUGPlayerWhen set to any value, enables the pane-geometry assertion, a development check that is off by default.
SUGAR_VIDEO_COLS, SUGAR_VIDEO_ROWSexamples/play.phpSeed the example's size, default 80 × 24, clamped to 10–200 × 5–80. The terminal's first size message overrides them.

Remote sources and security

Remote playback goes through Reel::openUrl(), which applies an SSRF guard through allowedHosts. Request headers are validated by HttpHeaders::parse(), which refuses list-shaped input and control bytes. The same headers reach ffmpeg for the video input and the audio companion, in each player's own dialect. FfmpegCommandBuilder::scrubbedEnv() strips variables that the child processes should not inherit.

use SugarCraft\Video\Source\HttpHeaders;

$headers = HttpHeaders::parse(['X-Session' => 'abc123']);
$ffmpegArg = $headers->toFfmpegHeaderString();   // CLI spelling for ffmpeg
$mpvArg    = $headers->toMpvHeaderFields();     // CLI spelling for mpv

Subtitles and accessibility

Reel::withSubtitles('clip.vtt') parses WebVTT, lenient enough for most SRT files, and paints the active cue as one caption line under the frame in every mode. WebVtt::cueAt(seconds) finds the active caption for a playhead position. The caption line is the one real-text channel in every graphics mode, so it is the text alternative for playback that image protocols draw as pixels.

Playback starts paused, and it never begins without a key press. Nothing moves unless the user asks for it, so there is no ambient motion for a reduced-motion setting to suppress. The README Accessibility section has the detail.

Examples

php examples/play.php --help
php examples/decode-frames.php 6

Testing

cd sugar-video && composer install && vendor/bin/phpunit

The suite is split across about 60 files under tests/. ReadmeSnippetsTest keeps the README's code samples in step with the API. Helpers under tests/Concerns hide or stub the ffmpeg and ffprobe binaries for the cases that need them absent or fake, so the decoder and probe paths run without a real toolchain.

Troubleshooting and FAQ

An mp4, avi or webm file does not play

Those formats decode through ffmpeg and ffprobe, and both must be on $PATH. Check with ffmpeg -version and ffprobe -version. Probe::hasFFmpeg() answers the same question from PHP.

A GIF or animated WebP fails to load

These decode in-process and need ext-gd. Check it with php -m. Animated WebP uses a RIFF walk that is pure PHP, plus GD for each frame.

There is no sound

Audio needs ffplay or mpv on $PATH. Without either binary the audio companion cannot start, so playback is silent. A source with no audio track also plays silently.

Video from a file is refused on Windows

FfmpegDecoder::open() refuses ffmpeg video on Windows with a guidance error, because the frame pump depends on stream_select(), which Windows does not support. GIF playback still works there.

A remote URL is refused

The host is not on the allowlist, or it resolves to a private or reserved address. Add the host to withAllowedHosts().

The picture is not what I expected in halfblock mode

Each cell covers two source rows, so a GIF fills the terminal at its full height in halfblock mode. Text modes keep the GIF at its native pixel dimensions. Set withSize() to fit the pane.

Playback starts paused

This is deliberate. Press Space to start. The player never moves on its own.

Architecture

video file (mp4/gif/avi/webm)
        |
        v
  VideoSource.probe           ffprobe JSON for the source
        |
        v
  DecoderFactory.new
        |
   +----+----------------------------+
   |                                 |
  GifDecoder (pure PHP, GD)     FfmpegDecoder (ffmpeg pipe)
   |                                 |
   +----+----------------------------+
        |
        v
  RgbFrame (rgb24, pre-scaled to cell size)
        |
        v
  FrameRenderer / RendererFactory   (Mosaic bridge for sixel, kitty, iterm2)
        |
        v
  Player (TEA model: tick() then view())
        |
        v
  Program (sugar-core: raw mode, alternate screen)

Known limitations

Upstream mapping

SugarCraftPrior artNotes
sugar-video (Player, Reel, the decoders)maxcurzi/tplay, seatedro/glyph, joelibaceta/video-to-asciiListed in docs/MATCHUPS.md as prior art. These are references, not ports. SugarCraft is developed as a native PHP project.
Graphics modes (sixel, kitty, iTerm2)sugar-imageDelegated to the sibling library that owns the protocol encoders.

Changelog and versioning

The package has no CHANGELOG file yet, and no sugar-video release tags exist. Consumers install the dev-master branch until a tagged release is cut. The monorepo sugar-video/ commit history is the record of changes. The Packagist page shows the current version.

Source & demos

Try the quickstart →