SugarVideo
Terminal video player
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
| Mode | Description | Terminal requirement |
|---|---|---|
| ascii | Grayscale luminance ramp | Any |
| ansi256 | 256-color cube + grey ramp | 256-color |
| truecolor | 24-bit RGB truecolor | 24-bit color |
| halfblock | 24-bit ▀ half-blocks, 2x vertical resolution | 24-bit color |
| quarterblock | 24-bit quarter-block characters, 2x2 sub-cell resolution | 24-bit color |
| sixel | Sixel raster graphics protocol (DEC) | Sixel-capable |
| kitty | Kitty graphics protocol (APC) | Kitty-compatible |
| iterm2 | iTerm2 inline image (OSC 1337) | iTerm2 / WezTerm |
| auto | Resolve 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
| Key | Action |
|---|---|
| Space | Pause / 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-9 | Seek to 0-90% of video duration |
| m | Cycle to next rendering mode |
| q / Esc / Ctrl-C | Quit |
Behavior (no keyboard shortcut)
| Setting | Behavior |
|---|---|
| resize | Terminal resize (SIGWINCH) re-scales video automatically |
| loop | Loop is set at open time via Reel::new()->withLoop(true)->play() (no keyboard shortcut) |
| subtitles | Attached at open time via Reel::withSubtitles() (no keyboard shortcut) |
| audio | No key toggles audio: Reel::withAudio() decides at open time; AudioPlayer::pause() / resume() (or mute() / unmute()) are the only levers |
API reference
| Class | Method | Description |
|---|---|---|
| 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 |
| Reel | withMode(Mode) | Set rendering mode |
| Reel | withSize(cols, rows) | Set terminal cell dimensions |
| Reel | withFps(?float) | FPS override (null = auto-detect) |
| Reel | withLoop(bool) | Enable/disable loop |
| Reel | withRamp(name) | Select the ascii/ansi256 luminance ramp (minimal, standard, dense) |
| Reel | withSubtitles(path) | Attach a WebVTT (or lenient SRT) caption track |
| Reel | withHeaders(headers) | Attach/replace request headers for remote sources |
| Reel | withAllowedHosts(hosts) | Pin the remote host allowlist |
| Reel | withCellPx(w, h) | Tell the player the terminal cell pixel size (graphics modes rasterize at cols·w × rows·h) |
| Reel | withAutoMode() | Switch to auto mode: the renderer ladder picks the best supported mode at open time |
| Reel | toPlayer() | 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 |
| Reel | play() | 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 |
| GifDecoder | open(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 |
| AnimatedWebpDecoder | open(...) / 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 |
| FfmpegDecoder | open(...) / 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 |
| RendererFactory | supportedModes() / supports(Mode) / support(Mode, cols, rows) / diagnose() | Which render modes this host can produce, and the probe report behind the answer |
| FfmpegCommandBuilder | scrubbedEnv() / 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.
| Method | Summary |
|---|---|
__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): string | Strip 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(): void | Spawn the audio subprocess (ffplay or mpv) if a suitable binary is available on this host. |
stop(): void | Stop the audio subprocess by terminating it in BOUNDED time. |
hasStarted(): bool | True 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(): void | Suspend audio playback by terminating the subprocess. |
resume(): void | Resume audio playback from the tracked position. |
position(): int | The 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(): void | M24: silence the companion — kills a live child and refuses future start()/resume() until unmute(). The video clock is unaffected. |
unmute(): void | |
isMuted(): bool | |
isPlaying(): bool | True when the audio subprocess is still running. |
tick(): void | The 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(): ?int | Return 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.
| Method | Summary |
|---|---|
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): self | Open 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): self | The 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): self | Factory for tests: create a Player with an injected decoder. |
init(): ?\Closure | |
update(Msg $msg): array | |
static clampCells(int $cols, int $rows): array | SV-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(): string | Render 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): array | Inclusive-box channel mean over the raw rgb24 grid (M21). |
withAudio(bool $on): self | M24: opt audio in or out (the 'm' key stays the mode cycle by design). |
withSeek(int $targetIndex): self | Seek 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(): float | Current playback position in content seconds (videoTime). |
headers(): array | The 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(): bool | Whether 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(): float | Total duration in content seconds, or 0.0 when unknown (a stream of indeterminate length, where totalFrames is 0). |
canSeekByTime(): bool | Ask 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): self | Seek to an absolute time in content seconds (clamped to [0, duration]). |
frameAt(float $sec): ?RgbFrame | Grab a single frame at $sec for a scrubber-hover thumbnail. |
stop(): void | Tear 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(): bool | Whether stop() has torn this player down (M15). |
pause(): self | Pause playback. Returns a new Player with paused=true. |
play(): self | Resume playback. Returns a new Player with paused=false and re-anchored clock so play-time accumulates correctly. |
withSubtitles(WebVtt $track): self | Attach a parsed subtitle track to the player. |
subscriptions(): ?\SugarCraft\Core\Subscriptions | |
teardownCmd(): ?\Closure | The 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.
| Method | Summary |
|---|---|
static setProgramRunForTesting(?\Closure $run): void | |
static new(): self | Construct an empty player with no source bound yet. |
static open(string $path): self | Open 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): self | Open a remote video source by http(s) URL. |
static preview(string $path): self | A glance-sized, silent Ansi256 preview (SV-L64/064). |
static captioned(string $path, string $subtitlePath): self | A clip paired with its caption track (SV-L64/064). |
static ambient(string $path): self | A silent looping wall piece (SV-L64/064). |
path(): string | The source video path this player was opened with ('' when unbound). |
mode(): ?Mode | The configured rendering mode (null means auto-detect). |
cols(): int | The configured terminal cell width. |
rows(): int | The configured terminal cell height. |
fps(): ?float | The configured FPS override, or null for auto-detect from probe. |
loop(): bool | Whether playback loops back to the start at end-of-stream. |
ramp(): string | The configured luminance ramp name ('minimal', 'standard', 'dense'). |
allowedHosts(): ?array | The configured remote-host allowlist, or null when host restriction is disabled (any host is accepted — SSRF surface; see openUrl()). |
headers(): array | The configured HTTP request headers for a remote source (empty otherwise). |
cellPx(): ?array | The caller-supplied pixel size of one terminal cell, as [width, height], or null when none was set. |
withMode(Mode $mode): self | Set the rendering mode. Returns a new Reel (immutable). |
withAutoMode(): self | Set the rendering mode to auto-detect (probed at play time). Returns a new Reel (immutable). |
withLoop(bool $loop = true): self | Enable (or disable) looping: replay from the start at end-of-stream instead of stopping. Returns a new Reel (immutable). |
withRamp(string $name): self | Set the luminance ramp. Returns a new Reel (immutable). |
withoutRamp(): self | Return to the default luminance ramp (SV-L50). |
withSize(int $cols, int $rows): self | Set the terminal size in cells. Returns a new Reel (immutable). |
withFps(?float $fps): self | Set a target FPS override. Pass null to use auto-detect from video probe. Returns a new Reel (immutable). |
withFrameBudget(float $ms): self | Set the per-tick decode budget (milliseconds) threaded to the built Player (SV-M19). Returns a new Reel (immutable). |
withSubtitles(string $path): self | Attach a subtitle file (WebVTT or SRT) to the player. |
withoutSubtitles(): self | Detach the subtitle track (SV-L50). |
withAudio(bool $on): self | M24: opt out of the audio companion for this Reel ('m' stays the mode key). |
withAllowedHosts(array $hosts): self | Restrict remote (http(s)) playback to a set of trusted hosts. |
withHeaders(array $headers): self | Set the HTTP request headers presented to a remote (http(s)) source. |
withoutHeaders(): self | Clear every request header (SV-L50). Returns a new Reel (immutable). |
withCellPx(int $w, int $h): self | Tell the player the real pixel size of one terminal cell. |
toPlayer(): Player | Build the playback Model from the configured options WITHOUT running it. |
play(): void | Run 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.
| Method | Summary |
|---|---|
static targetFrame(float $videoTimeSeconds, float $fps): int | Compute the target frame number from video content time. |
static shouldSkip(int $currentFrame, int $targetFrame): bool | Determine whether we are too far behind and must skip frames. |
static shouldHold(int $currentFrame, int $targetFrame): bool | Determine whether we are ahead and must hold/delay frames. |
Synthetic final class
Synthetic animated test-pattern generator.
| Method | Summary |
|---|---|
static defaultPath(): string | Default 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): string | Generate an animated rainbow-gradient GIF and return its path. |
SugarCraft\Video\Decode
AnimatedWebpDecoder final class
Animated WebP decoder — pure PHP + GD, no subprocess.
| Method | Summary |
|---|---|
__construct(int $cellPxW = 10, int $cellPxH = 20) | |
static supports(): bool | Whether 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): void | Test 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): bool | Cheap 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(): array | Per-frame display durations in milliseconds, container order. |
loopCount(): ?int | Total 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(): int | The 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(): bool | A fresh open() re-reads (and re-composites) the file, so a seek/resize rebuild is a plain close()+open() — same answer FfmpegDecoder gives. |
seeksBySeconds(): bool | SV-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): void | Test 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.
| Method | Summary |
|---|---|
open(string $source, int $cellsW, int $cellsH, float $fps, ?Mode $mode = null, float $startSec = 0.0, array $headers = []): void | Open the decoder for a source file, targeting a grid of cellsW x cellsH at approximately the given fps. |
getIterator(): \Generator | Yield the next RgbFrame, or null if there are no more frames. |
next(): ?RgbFrame | Return the next RgbFrame, or null if no more frames are available. |
close(): void | Close 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 = []): void | Re-open the decoder for a source file at the given grid size and fps. |
reopensInPlace(): bool | Whether reopen() is a faithful in-place rebuild of this decoder. |
seeksBySeconds(): bool | Whether a start-SECOND argument actually lands the playhead. |
DecoderFactory final class
Factory for creating the appropriate Decoder based on the source file.
| Method | Summary |
|---|---|
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): Decoder | Create an appropriate decoder for the given source file. |
static isLocalAnimatedWebp(string $source): bool | True 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.
| Method | Summary |
|---|---|
__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): array | Assemble 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): bool | Whether 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(): ?int | Returns 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(): bool | An 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(): bool | SV-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(): float | Return 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.
| Method | Summary |
|---|---|
__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(): ?string | m14: 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(): int | Conversions this decoder has actually performed (M40). |
emitCacheBytes(): int | Resident bytes currently held by the converted-frame cache (M40). |
static setEmitCacheCeilingForTesting(?int $bytes): void | Test 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(): ?int | The 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(): bool | True 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): bool | Whether $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(): bool | False — 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(): bool | SV-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.
| Method | Summary |
|---|---|
__construct(public string $bytes, public int $w, public int $h, public ?string $png = null) | |
toGd(): \GdImage | Convert the frame to a GD image. |
SugarCraft\Video\Msg
ResizeRebuildMsg final class
Deferred apply of a pending terminal resize .
| Method | Summary |
|---|---|
static instance(): self | Return the singleton ResizeRebuildMsg instance. |
TickMsg final class
Per-frame tick driving the video player.
| Method | Summary |
|---|---|
static instance(): self | Return the singleton TickMsg instance. |
SugarCraft\Video\Render
AsciiRenderer final class
A-11: ASCII / ANSI renderer — thin bridge over sugar-image's canonical AsciiRenderer.
| Method | Summary |
|---|---|
__construct(private readonly string $ramp = 'standard') | |
static colorModeFor(Mode $mode): AsciiColorMode | A-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".
| Method | Summary |
|---|---|
static new(): self | The marker instance — the only way to obtain one. |
Color final class
Color utility for packing RGB components into a single integer.
| Method | Summary |
|---|---|
static pack(int $r, int $g, int $b): int | Pack RGB components into a 0xRRGGBB integer. |
FrameRenderer interface
Contract for rendering an RgbFrame to an ANSI escape-string.
| Method | Summary |
|---|---|
render(RgbFrame $frame, Mode $mode): string | Render one RgbFrame to an ANSI string at the frame's native dimensions. |
cellDimensions(Mode $mode): array | The terminal cell dimensions a pixel of the GIVEN mode consumes. |
GraphicsRenderer final class
Graphics renderer — emits Sixel / Kitty / iTerm2 protocol output.
| Method | Summary |
|---|---|
__construct(private readonly Mode $mode, private readonly int $cellPxW = 10, private readonly int $cellPxH = 20) | |
render(RgbFrame $frame, Mode $mode): string | |
retirement(): string | The 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.
| Method | Summary |
|---|---|
render(RgbFrame $frame, Mode $mode): string | |
cellDimensions(Mode $mode): array |
LumaRamp final class
256-entry luminance-to-character lookup table.
| Method | Summary |
|---|---|
static ramp(string $name = self::DEFAULT_RAMP): array | Return the 256-entry character array for the named ramp. |
static isValidRamp(string $name): bool | Return true if the named ramp is a valid known ramp. |
static char(float $luma, string $ramp = 'standard'): string | Return the character for a given 0-255 luminance value. |
static compute(int $r, int $g, int $b): int | Compute 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().
| Method | Summary |
|---|---|
wireName(): string | The exact wire token this mode accepts (SV-M36). |
static wires(): array | The 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(): int | Source pixel-rows consumed per terminal cell. Half/quarter-block pack 2; graphics modes resolve in the renderer (treated as 1 here). |
colsPerCell(): int | Source pixel-cols per terminal cell. Quarter-block packs 2 across. |
isGraphics(): bool | Whether 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(): string | Human-readable description of the rendering mode. |
QuarterBlockRenderer final class
Quarter-block Unicode renderer — delegates to sugar-image's QuarterBlockRenderer.
| Method | Summary |
|---|---|
render(RgbFrame $frame, Mode $mode): string | |
cellDimensions(Mode $mode): array |
RendererFactory final class
Static factory for FrameRenderer instances.
| Method | Summary |
|---|---|
static diagnose(): ProbeReport | The terminal's capability report — probed once, memoized thereafter. |
static withKittyConfirmation(ProbeReport $report, bool $confirmed): ProbeReport | The 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): void | P1-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): void | Test seam: seed the capability memo (null = clear it). |
static setGraphicsGateForTesting(?\Closure $gate): void | SV-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(): bool | Whether 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(): array | Every Mode this terminal can honestly render right now. |
static supports(Mode $mode): bool | Whether this terminal can actually RECEIVE the mode's output. |
static support(Mode $mode, ?int $cols = null, ?int $rows = null): Support | The 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): Support | The 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): bool | The 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(): Mode | Return the best Mode enum case for the current terminal. |
static autoModeFrom(bool $sixel, bool $kitty, bool $iterm2, ?ColorProfile $profile, TermInfo $info): Mode | The 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): FrameRenderer | Pick the best renderer by probing terminal capabilities. |
static new(Mode $mode, string $ramp = 'standard', int $cellPxW = 10, int $cellPxH = 20): FrameRenderer | Return 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().
| Method | Summary |
|---|---|
isRenderable(): bool | |
notice(array $params = []): string | The 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.
| Method | Summary |
|---|---|
static none(): self | The empty set — no headers supplied, nothing to emit. |
static parse(array $headers): self | Validate raw caller-supplied headers into a trusted instance. |
isEmpty(): bool | True when there is nothing to add to the request. |
pairs(): array | The validated pairs, in submission order. |
userAgent(): ?string | The User-Agent value to pass as ffmpeg's -user_agent, or null when none was given. |
toFfmpegHeaderString(): ?string | The value for ffmpeg's -headers option: every header except User-Agent, each terminated by CRLF exactly as it will appear on the wire. |
toMpvHeaderFields(): array | The 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.
| Method | Summary |
|---|---|
static setClockForTesting(?\Closure $clock): void | Inject a deterministic clock (seconds since arbitrary origin) for the memo-expiry tests; null restores the live monotonic hrtime clock. |
static ffmpeg(): ?string | Path to the ffmpeg binary, or null if not found. |
static ffprobe(): ?string | Path to the ffprobe binary, or null if not found. |
static ffplay(): ?string | Path to the ffplay binary, or null if not found. |
static mpv(): ?string | Path to the mpv binary, or null if not found. |
static hasFFmpeg(): bool | True when the ffmpeg binary is available on this host. |
static clearBinaryCacheForTesting(): void | Drop 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.
| Method | Summary |
|---|---|
__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): self | The 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): self | Construct a VideoSource from a path and raw ffprobe JSON output. |
static probe(string $path, bool $hostRestricted = false): self | Probe 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.
| Method | Summary |
|---|---|
__construct(public readonly float $start, public readonly float $end, public readonly string $text) | |
contains(float $seconds): bool | Whether $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.
| Method | Summary |
|---|---|
cues(): array | |
isEmpty(): bool | |
static parse(string $text): self | Parse WebVTT (or SRT) text into a track. |
cueAt(float $seconds): ?string | The caption text showing at $seconds, or null when nothing is. |
static sanitizeForTerminal(string $text): string | The 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.
| Method | Summary |
|---|---|
static scrubbedEnv(): array | Environment for every media child: the parent env MINUS anything a spawned ffmpeg/ffplay/mpv/ffprobe must not honor. |
static isNetworkSource(string $source): bool | Whether the source is an http(s) URL (vs a local file path). |
static networkReconnectFlags(bool $hostRestricted = false): array | The http/https protocol reconnect block, as input options (so BEFORE -i). |
static headerInputFlags(HttpHeaders $headers): array | The 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): array | The header options for the mpv dialect: one repeatable --http-header-fields=Name: value per field. |
static inputSeekFlag(float $startSec): array | Fast 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): string | A float formatted for ffmpeg filter argv, locale-immune. |
static secondsFromMillis(int $ms): string | Milliseconds as a fixed S.mmm seconds string built from integer math. |
static ffplayAudioCommand(string $binary, string $source, int $seekMs, HttpHeaders $headers, bool $hostRestricted = false): array | The 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): array | The 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.
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
| Option | Type | Effect |
|---|---|---|
withMode() | Mode | Rendering mode. The default resolves the mode from the terminal environment (auto). |
withSize() | int, int | Cell width and height. The terminal's own size message overrides it. |
withFps() | ?float | Frame rate override. null auto-detects it. |
withLoop() | bool | Loop from end back to start. |
withRamp() | string | Luminance ramp for ascii and ansi256: minimal, standard or dense. |
withSubtitles() | string (path) | WebVTT or lenient SRT caption track. |
withHeaders() | array | Request headers for remote sources, validated by HttpHeaders. |
withAllowedHosts() | array | Host allowlist for remote sources. Pin it in production. |
withCellPx() | int, int | Terminal 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() | bool | Starts the audio companion (ffplay or mpv) with the video. |
Environment variables
| Variable | Read by | Effect |
|---|---|---|
SUGAR_VIDEO_DEBUG | Player | When set to any value, enables the pane-geometry assertion, a development check that is off by default. |
SUGAR_VIDEO_COLS, SUGAR_VIDEO_ROWS | examples/play.php | Seed 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
examples/play.php [path|synthetic] [mode]is the full player. It accepts--subs=FILEand--help. It is interactive, so run it by hand.examples/decode-frames.php [frames]decodes a synthetic GIF with the pure-PHP decoder and prints each frame. It needs no terminal, exits 0 on success, and removes its temporary files.
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)
- Decode:
FfmpegDecoderrunsffmpegfor raw RGB frames, pre-scaled to cell dimensions.GifDecoderandAnimatedWebpDecoderdecode in-process. Local GIF and animated WebP sources decode in-process. - Render: the text modes assemble their SGR cell grid with sugar-cellbuffer. The graphics modes delegate to sugar-image. Color mapping uses sugar-colorprofile.
- Pace:
Syncaligns ticks, with no busy wait. Deltas accumulate on a monotonic base, and one tick charges at mostPlayer::MAX_TICK_DELTA_SECof content time. - Audio:
AudioPlayerrunsffplayormpvas a companion. The player's own monotonic clock stays master, so audio may drift but never drives pacing.
Known limitations
- Repaint granularity is rows, not cells. The player returns the full frame from
view()on every tick. The default renderer re-sends each changed row, so one dirty cell costs a row of output. - Audio plays at 1.0× regardless of speed. The
[and]keys change only the video pacing. A/V diverges at other speeds. - Seeks are fast but keyframe-snapped. ffmpeg input seeking lands on the keyframe at or before the target, so the first frame can be a little less exact than output seeking.
- Sixel frames cost PHP time. The pure-PHP encoder spends more CPU per large frame than a native encoder would. No child process is spawned from the render path.
- Audio pause and seek are approximate. Pause ends the audio child and resume starts a new one from the banked position. The audio clock is quantized to the last pause boundary.
- Audio headers reach only two dialects. A per-request nonce, or a cookie that the video side obtained by redirect, will not reach the audio companion.
Upstream mapping
| SugarCraft | Prior art | Notes |
|---|---|---|
sugar-video (Player, Reel, the decoders) | maxcurzi/tplay, seatedro/glyph, joelibaceta/video-to-ascii | Listed 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-image | Delegated 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.