sugarcraft / sugar-video
Terminal video player for SugarCraft — plays mp4 (and more) by decoding frames on the fly and rendering them to ASCII / ANSI / truecolor half-block / sixel / kitty output.
Requires
- php: ^8.3
- ext-mbstring: *
- sugarcraft/sugar-animation: dev-master
- sugarcraft/sugar-cellbuffer: dev-master
- sugarcraft/sugar-colorprofile: dev-master
- sugarcraft/sugar-core: dev-master
- sugarcraft/sugar-image: dev-master
Requires (Dev)
- phpunit/phpunit: ^10.5
- sugarcraft/sugar-testing: dev-master
Suggests
- ext-gd: Required for .gif playback and animated .webp decoding (the pure-PHP routes; no ffmpeg needed). mp4/avi/webm need the ffmpeg and ffprobe binaries on $PATH — a runtime toolchain, not a Composer package.
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 01:04:14 UTC
README
Formerly published as
sugarcraft/sugar-reel(renamed 2026-10). Namespace changed:SugarCraft\Reel\→SugarCraft\Video\.
Terminal video player — plays mp4 / gif / avi / webm / animated webp and more on
the fly, rendering each frame as ASCII, ANSI 256-color, truecolor half-blocks,
or via modern graphics protocols (sixel / kitty / iTerm2). Like mpv -vo tct,
but in PHP and reusing the SugarCraft rendering stack throughout.
composer require sugarcraft/sugar-video
use SugarCraft\Video\Reel; // Play a video with auto-detected terminal capability — it opens paused; // Space starts the motion. Reel::open('clip.mp4')->play();
Reel is the everyday entry point: an immutable description of what to
play — source, render mode, size, ramp, subtitles, audio — finished with
play(), which builds its own sugar-core Program, owns the event loop,
and blocks until you quit. Player is the MVC-style Model–Update–View runtime underneath it
(init()/update()/view()); a host that already owns a program loop
mounts the model itself via Reel::toPlayer(), described under
“Embedding the player without owning the loop”.
Status: complete — full implementation with ffmpeg decode pipe, pure-PHP GIF fallback, all rendering modes (ascii/ansi256/truecolor/ halfblock/quarterblock/sixel/kitty/iterm2), delta repaint, seek, speed control, and a runnable example.
Install
composer require sugarcraft/sugar-video
Requires:
- PHP 8.3+
ffmpegandffprobein$PATHformp4/avi/webmplayback. The effective version floor for plain and network playback is ffmpeg ≥ 4.0. Three facts fix it in place:- The reconnect option block carries only options that old builds know —
-reconnect/-reconnect_streamedsince 3.3,-reconnect_delay_maxsince 4.0. - The 5.1-only
-reconnect_on_network_errorwas deliberately dropped, because unknown input options abort the open on older builds. - Binding a host allowlist (
openUrl(..., allowedHosts:)/withAllowedHosts()) raises the floor to 4.4, where themax_redirectsno-redirect transport pin was introduced.
- The reconnect option block carries only options that old builds know —
ext-gdfor.gifplayback (pure-PHP fallback, no ffmpeg needed — for local files; a remote.gifURL routes throughffmpegbecause the pure-PHP decoder has no network transport)ext-gdbuilt with WebP for animated.webpplayback, via a pure-PHP container walk plus per-frame GD decode — no ffmpeg needed. Choosing the in-process route is deliberate, not a capability gap: current ffmpeg builds decode animated WebP fine, but the pure-PHP path needs no external toolchain, spawns no child, and decodes deterministically. The same local-only caveat applies to remote.webp: animated sniffing never touches the network, so those sources go throughffmpegtoo. On an ffmpeg-less host both remote routes fail loudly with thedecoder.ffmpeg_missingmessage.ffplayormpvin$PATHfor audio output. With neither, playback is silent but not secretly so:AudioPlayer::start()announces the missing binary once onerror_logand stays off. Video playback is unaffected — audio is optional by contract.- A terminal with at least 256-color support for ANSI modes
Usage
# Built-in synthetic test pattern (no video file needed) php examples/play.php synthetic # Play a real video file php examples/play.php video.mp4 # Force a specific rendering mode php examples/play.php video.mp4 halfblock php examples/play.php video.mp4 ascii # Force auto mode (probe terminal, pick best available) php examples/play.php video.mp4 auto # Seed the first frame's size — the terminal's own size message overrides # it, so a live resize always wins SUGAR_VIDEO_COLS=120 SUGAR_VIDEO_ROWS=40 php examples/play.php synthetic
These demos resolve the autoloader from a repo checkout (the library's own vendor/ or the monorepo root) and exit with an actionable error elsewhere — when sugar-video is consumed as a Composer dependency, examples/ ships inside vendor/sugarcraft/sugar-video/ and works the same way only if that copy's own dependencies are installed; for your project, script the API below instead.
Ready-made compositions
Three static presets (SV-L64), each one line of this README and each nothing but shorthand for the public wither chain it composes — ReelTest pins them prop-for-prop:
Reel::preview('clip.mp4')->play(); // glance: small cells, Ansi256 rung, silent Reel::captioned('clip.mp4', 'clip.vtt')->play(); // clip paired with its caption track Reel::ambient('art.mp4')->play(); // silent open-time loop, auto ladder picks the rung
Rendering modes
| Mode | Description | Terminal requirement |
|---|---|---|
ascii |
Grayscale luminance ramp ( .,:;i1tfLCG08@) |
Any |
ansi256 |
256-color cube + grey ramp | 256-color |
truecolor |
24-bit RGB truecolor | 24-bit color |
halfblock |
24-bit ▀ half-blocks, 2× vertical resolution |
24-bit color |
quarterblock |
24-bit quarter-block characters, 2×2 sub-cell resolution | 24-bit color |
sixel |
Sixel graphics protocol (DEC) | Sixel-capable |
kitty |
Kitty graphics protocol (APC \x1b_G) |
Kitty-compatible — TERM=xterm-kitty is only a hypothesis; the terminal must answer the APC a=q query on a tty (P1-13b), otherwise kitty is refused or skipped by auto |
iterm2 |
iTerm2 inline image (OSC 1337) | iTerm2 only — WezTerm is recognized as a TrueColor seat and never an OSC 1337 one, so explicit iterm2 there takes the typed refusal |
auto |
Selector, not a ninth mode: resolves the terminal from its environment at open and picks the best mode it can render — a lookup table, with one exception: a Kitty claim is confirmed by an APC a=q query on a tty, the only tty I/O in the selector (see the note below the table). There is no Mode::Auto case — Mode::from('auto') throws a ValueError; Mode::AUTO_WIRE carries the token and Mode::wires() the full accepted list |
— |
Styling convention, stated once: a backticked lowercase token (halfblock)
is a selectable MODE — the CLI and wire vocabulary; capitalized names (Sixel,
Kitty, iTerm2) refer to the terminal PROTOCOL behind a rung; bare prose like
half-block describes the rendering technique, not the mode token.
Each row's mode column is that case's exact wire token: Mode::wireName()
returns it, and it equals strtolower($mode->name) for every case (pinned),
so a host that persisted the lower-cased enum name re-imports verbatim with
Mode::from($mode->wireName()). Mode::wires() — auto first, then the
eight case tokens — is the single source the CLI validates against; there
are no further aliases.
Auto mode negotiates with the terminal only to confirm a Kitty claim (below).
Mosaic::diagnose() (for
sixel/kitty/iTerm2) delegates to sugar-colorprofile's TerminalProbe: a
lookup table over TERM_PROGRAM/TERM and friends that, despite the
historical name, issues no raw OSC query round-trips; the ANSI fallback
reads SugarCraft\ColorProfile\Probe::colorProfile() and a pure TermDb
match chain over the captured environment. The consequence is honest: seats
that could render graphics but are absent from the table (foot, plain
xterm, contour, kitty under tmux) never auto-ascend to a graphics rung — and WezTerm,
which IS in the table, is listed there for its TrueColor upgrade only: the probe
never answers Capability::ITerm2 for it, so the iTerm2 rung stays as closed
to WezTerm auto as to foot.
The kitty rung needs a confirmed claim. RendererFactory::diagnose() starts
from sugar-colorprofile's Capability::KittyKeyboard, which its probe sets
when TERM equals xterm-kitty, and drops that claim unless sugar-image's
Detect::probe() gets the Kitty APC a=q reply on a tty (P1-13b). The same
contract applies to supports(), support(), auto() and the explicit door,
so a TERM-only Kitty seat that never answers is not handed APC frames. With no
tty the claim is dropped and auto falls back to the palette ladder.
The confirming probe runs once per process, at the first diagnose() call on a
Kitty seat (the first auto, supports() or support(), which in a player is
the first video open or the first m keypress). It is a full sugar-image
Detect::probe(), so that call does tty I/O, can wait up to the 300 ms APC
window plus the DA1 window, and runs inside the caller's update loop. Keys typed
during that wait are held in sugar-image's stray-input store, which only the
candy-code launcher drains, before its TUI starts; a mid-session probe does not
replay them. Probing at boot, before the TUI starts, avoids that loss; this
library does not do it, and the cost is accepted as documented here. The
sixel and iTerm2 rungs still use sugar-colorprofile's table as before.
Luminance ramp selection
ASCII/ANSI256 text modes use a luminance ramp to map pixel brightness to characters. Three named ramps are available:
| Ramp | Characters | Best for |
|---|---|---|
minimal |
.:-=+*#%@ |
Low-resolution / high contrast |
standard |
.,:;i1tfLCG08@ |
General use (default) |
dense |
.\`^",:;Il!i><~+_-?][}{1)(|\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$ |
High-fidelity ASCII art |
use SugarCraft\Video\Reel; // Use the dense ramp for more detailed ASCII output Reel::open('video.mp4')->withRamp('dense')->play();
Remote and embedded playback
Authenticated / signed streams
Reel::openUrl() plays an http(s) stream and re-presents request headers on
every open and every decoder rebuild (a seek or a resize re-spawns ffmpeg, so
a short-lived signed URL or bearer token must be re-sent each time):
use SugarCraft\Video\Reel; Reel::openUrl( 'https://cdn.example.com/private/clip.mp4', headers: [ 'Authorization' => 'Bearer <token>', 'User-Agent' => 'my-app/1.0', ], allowedHosts: ['cdn.example.com'], // optional host allowlist )->play();
Header validation
Three rules, checked at the boundary — each one throws
InvalidArgumentException before ffmpeg is ever spawned:
- A name or value must not contain any C0 control except HTAB, or DEL. That set covers the classic CR, LF and NUL injection bytes (HPP / request-splitting).
- A name must not be empty, and a name must not contain a colon.
- An entry that is not a well-formed field line is rejected as malformed.
A User-Agent value is passed to ffmpeg -user_agent; every other header
rides in a single -headers block. Both flags are emitted only for network
sources — for a local file they are dropped and a reason is logged.
openUrl() positional migration
Migration note: the second parameter used to be $allowedHosts; it is
now $headers (prefer named arguments). The old positional shape fails
loudly: any list-shaped array is rejected outright as the legacy
allowedHosts shape (it gets its own migration message) — even a list
carrying otherwise-valid header field lines — and null fails as a
TypeError.
Host allowlist and SSRF
Non-http(s) URL schemes (rtsp://, rtmp://, …) are not opened by
openUrl(). Calling openUrl() without allowedHosts: also logs a
one-line SSRF advisory (ssrf.no_allowlist, host only — never the path or
query): ffmpeg resolves DNS and follows redirects, so an unbounded remote URL
can reach internal hosts.
With an allowlist bound, the policy is "first-hop string + no-redirect
transport". Parser-divergent raw authorities (a backslash, ;, @, or %
in the host region) are refused outright. Every network child — ffprobe,
the ffmpeg decoder, and the audio companion — is pinned to
max_redirects=0 (FfmpegCommandBuilder::ALLOWED_MAX_REDIRECTS), so a
listed host cannot answer with a 302 into the internal range. A legitimate
redirecting CDN must have its redirect TARGET allowlisted too.
Environment scrubbing — which variables are stripped
Every child the library spawns — the transient ffprobe probe, the ffmpeg
decoder, and the ffplay/mpv audio companion — starts with a scrubbed copy
of the parent environment. Any variable whose name contains PROXY,
SECRET, TOKEN, KEY, CREDENTIAL, or PASSWORD (case-insensitive,
FfmpegCommandBuilder::scrubbedEnv()) is removed: those binaries run external
code against your sources and have no need for credentials. A missing or
empty PATH is restored to /usr/local/bin:/usr/bin:/bin so discovery
still works.
// Mutate headers fluently on an existing Reel (validated the same way): $reel = $reel->withHeaders(['Cookie' => 'session=…']);
Embedding the player without owning the loop
Reel::play() builds its own sugar-core Program and blocks. To drive playback
from a host that already owns a Program/event loop, use Reel::toPlayer() to
get the Player model paused and mount it yourself. Building the model
opens the source. The probe spawns a short-lived ffprobe child that is
reaped at once. Pinning the frame rate — withFps/$fpsOverride — skips the
probe child entirely, and with it the duration timeline and the audio
companion: those are probe answers. Sources routed through ffmpeg
(mp4/avi/webm, plus remote
.gif/.webp) spawn their ffmpeg decoder child immediately — a host that
mounts and never starts must still call stop() to release it. Locally
decoded GIFs and animated WebP ride pure PHP/GD in-process and cost no child.
Under the full-frame contract, Player::view() returns the entire current frame
on every call and diffs nothing itself; repaint efficiency comes from sugar-core's
Renderer (changed rows re-sent by default, per-cell diffing only under the
opt-in cellDiffRenderer), never from the model.
$player = Reel::openUrl($url, $headers)->toPlayer(); // paused; decoder child already spawned // Mount $player in your own Program, or fold it into a larger Model. // play()/pause() are immutable — they return a NEW Player, so re-bind it: // calling $player->play(); as a statement leaves the mounted model paused // while the shared audio companion has already resumed in place. $player = $player->play(); // un-pause: re-anchors the play clock on the new model // When the host leaves the player screen, release the child processes: $player->stop(); // idempotent — stops audio companion + closes decoder/ffmpeg
Or build the model directly: Player::open() takes the same source and
geometry a Reel would forward, and everything below applies unchanged.
use SugarCraft\Video\Player; $player = Player::open('clip.mp4', cellsW: 80, cellsH: 24); // Run it (Space=play, q=quit). (new \SugarCraft\Core\Program($player))->run();
Host contract — the caller that owns the loop is responsible for:
- Resize: forward terminal resizes to the player as a
SugarCraft\Core\Msg\WindowSizeMsg. A player mounted in sugar-core'sProgramgets this forwarding for free —Programinstalls theSIGWINCHhandler and dispatches the live size — which is whyReel::play()rescales without any wiring in the caller; only a host that owns its own loop forwards the signal by hand. Wherepcntlis absent (a stock Windows CLI) no signal can be caught: close and re-open the player at the new geometry instead.Playerclamps columns to[10, 200]and rows to[5, 80](theMIN_COLS/MAX_COLS/MIN_ROWS/MAX_ROWSconstants) and ignores a resize that does not change the clamped cell grid. A change rebuilds the decoder off the render hot path (inupdate, never inview) and off the signal itself: the handler only records the target and returns a short debounce command, and the re-spawn happens once the burst settles — so dragging a terminal edge costs oneffmpegre-open, not one per character cell. The host must actually run the commandupdate()returns, or the player keeps decoding at the superseded size. - Quit keys: decide when to quit. Standalone playback quits on
q,Esc, orCtrl-Cand each of those paths callsPlayer::stop()first; a host embedding the player may route different keys but must still callstop()on teardown so noffmpeg/audio child is orphaned. - Tick: the player self-schedules with
Cmd::tick()(SugarCraft\Core\Cmd) while playing; when the timer fires the host's loop feeds the player aSugarCraft\Video\Msg\TickMsgthroughupdate()— do not poll it from a separate timer.toPlayer()returns it paused — start it with$player = $player->play()(re-bind:play()returns a new Player; the statement form would leave the mounted model paused while the shared audio companion resumes) or sendSpacethroughupdate(). - Source binding:
toPlayer()requires a bound source (a path or URL). An unboundReel::new()throwsInvalidArgumentExceptionrather than silently substituting the synthetic pattern thatplay()uses.
Tell the player how big one cell is
In the graphics modes (sixel, kitty, iterm2) the terminal's cell pixel size
is a decode input: the frame is rasterized at cols × cellPxW by
rows × cellPxH so the image fills the pixel box instead of being resampled up
from one pixel per cell. Only the host knows that number, so Reel accepts it
through withCellPx() and forwards it to Player::open() (and to play(),
which builds the same player internally):
use SugarCraft\Image\Mosaic; use SugarCraft\Video\Reel; use SugarCraft\Video\Render\Mode; // Mosaic::auto()/probe() runs Detect::probe(), whose XTWINOPS 16t round-trip // yields ['cellWidth'=>…, 'cellHeight'=>…] — or null whenever there is no // interactive TTY (CI, piped stdout) or the terminal does not answer within // ~100 ms. Cache it at the application boundary; do not re-query per frame. $cell = Mosaic::auto()->fontSize(); $reel = Reel::open('clip.mp4') ->withMode(Mode::Kitty) ->withSize(120, 45); if ($cell !== null) { $reel = $reel->withCellPx($cell['cellWidth'], $cell['cellHeight']); } // 120·cellWidth × 45·cellHeight pixels when measured; the historical // 10×20 assumption when the terminal gave nothing back. $player = $reel->toPlayer();
Reel deliberately does not probe the terminal itself. A query issued
from inside a Model builder would block, and it would contend with whatever
the embedding program already owns — so the measurement is injected.
Callers that never withCellPx() keep the long-standing 10×20 assumption
unchanged (it is Player::open()'s own default), and cellPx() returns
null until one is supplied. A non-positive dimension throws
InvalidArgumentException.
Feeding your own decoder
Player::open() builds its decoder from a source path. When frames come from
somewhere else — a server transcoding to RGB24 over a socket, a renderer you
own, a test double with canned bytes — Player::fromDecoder() takes any
Decoder instead, and Player::openForTest() keeps the same seam scriptable
(injected clock, unbounded walk). Implementing the interface is the whole
contract:
| Member | Contract |
|---|---|
open(source, cellsW, cellsH, fps, mode, startSec, headers) |
bind the source; validate at this boundary (headers land typed, HttpHeaders) so internals trust their data |
getIterator() |
generator over the stream |
next(): ?RgbFrame |
next frame; null means a clean end of stream, never a failure — FfmpegDecodeFailure is reserved for a child that died while frames were expected, and any other exception still propagates untouched to the host |
close(): void |
teardown; idempotent; no child or descriptor outlives it (the repo-wide child-lifetime law) |
reopen(source, cellsW, cellsH, fps, mode, startSec, headers) |
rebuild at a new geometry — in place when you can, faithful either way |
reopensInPlace(): bool |
true is the decoder saying “reopen me, I can retarget myself”; false is “I am a plain stream — rebuild me from the source path”. The Player routes seeks, resizes and mode changes on this answer, never on a path-string guess |
seeksBySeconds(): bool |
true is “$startSec lands the playhead” (ffmpeg -ss before -i; GIF/WebP cursor jump over the captured bytes); false is “I replay from my own head” |
Player::canSeekByTime() folds both answers together with the source binding:
a host (candy-top's frame RPC is the motivating caller) asks it once before a
time seek or a thumbnail grab instead of discovering the wall as a runtime
throw. All three shipped factory decoders answer seeksBySeconds() true;
test doubles that replay from their head answer false, exactly as the
capability says.
The frame itself is a readonly RgbFrame: $bytes raw RGB24, row-major,
exactly w * h * 3, $w/$h in pixels, and an optional $png carrying a
pre-encoded full-resolution PNG for the graphics rungs (a PNG-only frame uses
bytes: ''); toGd() converts under ext-gd.
GifDecoder and AnimatedWebpDecoder additionally answer
loopCount(): ?int over the authored container bytes with one shared shape —
infinite is null, an authored play count is its integer total (raw-0
means forever; libnsgif's reading, mirrored by the WebP RIFF walk) — plus
playOnce() for the explicitly-authored single playthrough. This is file
state, not playback policy: the Player's own loop flag still decides
restart-at-EOF.
Two traps worth knowing before you write the host loop:
frameAt()rewinds, throws, or answers null. On a decoder that reopens in place it reopens at the hovered second, takes one frame, and reopens at the current playhead in afinally— scrubbing while playing cannot desync the live stream. On a factory-owned decoder it spawns a throwaway-ssread and closes it without disturbing the live one; an unbound factory player has no path to respawn from and throwsLogicException— askcanSeekByTime()first. Results are memoised one thumbnail per second with a spawn floor, so mouse scrubbing is cheap. A decode failure during the peek is announced once onerror_logand answers null — an advisory read never ends the session.- A failed seek ends loudly; it never escapes.
withSeek()andseekToSeconds()respawn the decoder on the seconds route, and a respawn that dies used to throw itsFfmpegDecodeFailurethrough those public doors. They now return an ended Player carrying the failure row — the same shape theupdate()choke point gives a dead pump — so a direct RPC seek needs no ffmpeg-specific catch.
Subtitles
Subtitles are WebVTT text that paints beneath the frame during playback. Attach
a track to a Reel and it flows through to the player untouched:
use SugarCraft\Video\Reel; // The .vtt is read and parsed when play()/toPlayer() builds the Player; a // missing or unreadable track is announced via error_log (subtitle.unreadable // / subtitle.too_large) and playback continues without captions — "no // subtitles" rather than a fatal, but never a silent drop. Reel::open('clip.mp4') ->withSubtitles('clip.vtt') ->play();
Format support. WebVtt::parse() accepts standard WebVTT and is lenient
enough to read most .srt files directly: numeric cue indices and ,
millisecond separators are tolerated, NOTE/STYLE/REGION blocks are
skipped, inline tags (<i>, <c>, cues' <c.class>) are stripped, and HTML
entities are decoded. Cue identifiers and cue settings lines
(position:, align: …) are parsed away but not honored — the renderer owns
placement. A track over WebVtt::MAX_CUES (10,000) cues is truncated to that
bound.
Where they paint. In every rendering mode the active cue for the current
video time is appended as one caption line directly below the frame,
left-aligned, truncated or space-padded to the player's cell width (the
one-line-per-row invariant). Cue lookup (WebVtt::cueAt()) binary-searches
the timeline for the rightmost cue starting at or before the position, then
walks back until a cue actually contains it — O(log n) plus worst-case O(k)
over the cues walked back, bounded by the parser's MAX_CUES cap — so an
attached track adds a bounded per-frame lookup, not a free one. There
is no keyboard shortcut: the toggle is attaching (or not attaching) the track
at open time.
Hosts that want their own placement can skip the integration entirely — parse
the track with WebVtt::parse() and hand the object to
Player::open(subtitles:), or query cueAt() yourself and compose the text
into your own view.
Keyboard controls
Playback starts paused — Space is the first key you will press.
| Key | Action |
|---|---|
Space |
Pause / resume |
← |
Seek backward 10 frames |
→ |
Seek forward 10 frames |
[ |
Decrease playback speed (−0.25×, min 0.25×) |
] |
Increase playback speed (+0.25×, max 4.0×) |
0–9 |
Seek to 0–90% of video duration |
m |
Cycle to next rendering mode — the cycle walks only the modes this terminal can actually receive (graphics rungs gated by RendererFactory::supports(); text rungs always cycle) |
q / Esc / Ctrl-C |
Quit |
Behaviour (no keyboard shortcut)
| Setting | Behaviour |
|---|---|
resize |
Terminal resize (SIGWINCH) re-scales video automatically — under Reel::play() the Program host installs the handler; embedding hosts forward WindowSizeMsg themselves (see Host contract) |
loop |
Loop is set at open time via Reel::new()->withLoop(true)->play() (no keyboard shortcut) |
subtitles |
Attached at open time via Reel::withSubtitles() (the example takes --subs=FILE; no keyboard shortcut). The active cue keeps painting while paused — it follows the playhead, not the clock |
audio |
No key toggles audio: on/off is chosen at open time via Reel::withAudio(), and AudioPlayer::pause() / resume() (or mute() / unmute()) are the only levers, never bound to a key |
Accessibility
- The caption line is the one real-text channel in this player. When a track
is attached with
Reel::withSubtitles(), the active cue renders as plain text one row below the frame in every rendering mode — that row is what a screen reader, a terminal text capture, or a transcript tool can read. The cue follows the playhead, not the wall clock: a paused player keeps painting the active cue (Space at 12.3 s holds the sentence you are reading; a seek repaints the cue at the landed time) — pause is a legibility state, not a subtitle freeze. The image protocols (Sixel, Kitty, iTerm2) draw frames as graphics and emit no text at all, so a video without a caption track is opaque to assistive technology: the track is the text alternative for the visual channel in the WCAG 1.2 sense. - Everything is operable from the keyboard (see Keyboard controls); no pointer is required, and what has no key — loop, subtitles, audio — is fixed at open time. There is deliberately no audio-mute key: sound is the host's open-time decision, not something a stray keystroke changes mid-playback.
- Motion is never imposed: playback starts paused and waits for
Space. A reduced-motion host is honored by that law, stated in full under Reduced motion and paused start.
Reduced motion and paused start
Opening a source starts no motion. Player::open() pulls a single poster
frame and returns the model paused — the first screen is a still with
real content, and nothing decodes or repaints on its own. The poster IS
frame 0 (SV-M39): the model keeps it instead of rewinding the decoder, so
opening costs exactly one decode child, and the first advance after Space
shows frame 1 — the playhead never replays what the poster already painted.
Reel::play()
runs that same model, so even the one-line quickstart waits for Space
before a single frame moves.
A REDUCE_MOTION host is honored by that law rather than by a switch: the
player reads no environment variable to decide whether to move, because it
never moves unsolicited in the first place. Once you press Space, the
speed is yours ([ and ], floor 0.25×) and Space stops the motion
again at any point.
Architecture
video file (mp4/gif/avi/webm)
│
▼
┌───────────────────┐ ┌─────────────────┐
│ VideoSource::probe│ │ DecoderFactory │
│ (ffprobe JSON) │────▶│ ::new() │
└───────────────────┘ └────────┬─────────┘
│
┌────────────┴────────────┐
│ │
GifDecoder FfmpegDecoder
(pure PHP / GD) (ffmpeg pipe)
│ │
└────────────┬───────────┘
▼
┌──────────────────────┐
│ RgbFrame (rgb24) │
└──────────┬─────────────┘
│
┌─────────┴──────────────┐
│ FrameRenderer / │
│ Mosaic bridge │
└─────────┬──────────────┘
│
┌──────────┴───────────────┐
│ Player (MVC-style │
│ Model–Update–View) │
│ tick() → view() │
└──────────┬───────────────┘
│
┌─────────▼──────────────┐
│ Program (sugar-core) │
│ raw mode + alt screen│
└────────────────────────┘
- Decode:
FfmpegDecodershells out toffmpegfor raw RGB frames (pre-scaled to cell dimensions).GifDecoderwraps sugar-animation's pure-PHP GIF decoder. - Render: Delegates to sugar-image for sixel/kitty/iTerm2. Uses sugar-colorprofile for color mapping. Text modes assemble their SGR cell grid with sugar-cellbuffer; the delta repaint belongs to sugar-core's
Renderer, which re-sends only the rows that changed by default and switches to per-cell diffing only when the host opts intoProgramOptions::$cellDiffRenderer. - Pace:
Cmd::tick()alignment viaSync, no busy-waiting. Tick deltas accumulate on a monotonic base (SV-M20:hrtime, notmicrotime) — an NTP step or a laptop-suspend resume can no longer fast-forward thousands of frames or freeze playback, and one tick charges at mostPlayer::MAX_TICK_DELTA_SECof content time whatever the clock claims. - Audio:
AudioPlayershells out toffplay(-nodisp -autoexit) ormpv(--no-video --really-quiet, plus--start=…son a banked resume) as the audio output companion; the Player's own (monotonic) clock stays master (audio may drift; it is never the pacing source).
Prior art
The decode → render → pace pipeline draws on three terminal-video projects, credited here:
- maxcurzi/tplay — Rust terminal media player.
- seatedro/glyph — edge-aware ASCII/ANSI video renderer.
- joelibaceta/video-to-ascii — Python video-to-ASCII player.
The rendering stack is reused from the SugarCraft ecosystem rather than reinvented:
- sugar-image — image → cell renderers and the dithering they apply
- sugar-animation — the pure-PHP GIF decoder that
GifDecoderwraps (frame downsampling is NOT its doing: ffmpeg pre-scales video frames, and text-mode packing goes throughPlayer::areaAverageRgb()) - sugar-colorprofile — color mapping
- sugar-core — Model–Update–View runtime, frame pacing, and the row-diffing renderer
- sugar-cellbuffer — the cell grid the text-mode renderer assembles each frame onto
Where this fits. The known in-ecosystem dependent is candy-code, which mounts the player as its video screen. There is no sibling video library to choose instead: for still images use sugar-image, for GIF primitives without playback use sugar-animation.
Sixel encoding is pure PHP (no external accelerator). sixel mode
encodes through sugar-image's SixelRenderer. The former preference for an
external chafa binary on PATH was retired once candy-image shipped as the
chafa frontend — sugar-image is now the single sixel encoder in the
ecosystem. Each mode decodes its frames at the pixel grid it renders:
graphics modes at cells·cellPx, text modes at the mode cell grid. The
pure-PHP encoder therefore needs no upscaling, and the DCS stream it emits is
protocol-conformant output — exactly the shape a sixel-capable terminal
expects.
Known limitations
-
Repaint granularity is rows, not cells. The Player returns the full frame from
view()on every tick and sugar-core's default renderer re-sends each changed ROW, so one dirty cell costs a row of output on otherwise-static frames. Cell-granularity diffing exists but is opt-in viaProgramOptions::$cellDiffRenderer. -
Audio plays at 1.0× regardless of playback speed. Changing speed with
[/]only affects video pacing. The audio companion (ffplay/mpv) always plays at normal speed. A/V will diverge noticeably when using speeds other than 1.0×. -
An option-shaped audio source is refused silently. A video path that begins with
-is never handed to ffplay/mpv: both parse leading-dash arguments as command-line options, andmpv --script=executes arbitrary Lua. The audio companion simply stays off for such a source (video playback is unaffected) — the route speaks only plain local paths and http(s) URLs, so a--prefixed source is never legitimate anyway. The refusal is currently silent; a visible announcement may be added. -
Seeking repositions audio but not frame-exactly. A seek creates a new AudioPlayer at the correct offset, but the video frame timing and audio timing are only approximately synchronized (frame-skip resync keeps them close at 1.0×).
-
GIF playback fills the terminal in
halfblockmode (each cell = 2 source rows). In text modes (ascii/ansi256/truecolor) the GIF renders at its native pixel dimensions without 2× vertical scaling. -
Sixel frames cost PHP time. The pure-PHP encoder spends more CPU time per large sixel frame than a native accelerator would; no child process is ever spawned from the video render path.
-
Seek is fast, slightly less frame-exact (keyframe snap).
seekToSeconds()uses ffmpeg input seeking (-ssplaced before-i), which decodes from the keyframe at or just before the requested time rather than walking the whole file. That is what makes scrubbing a multi-GB network stream instant; the trade-off is that the landed frame can be a touch less frame-exact than output seeking, andvideoTime/frameIndexare set to the requested target, so the on-screen clock can lead the first displayed frame by up to one GOP on sparsely-keyed sources. Index-based seeks (withSeek()— the arrows and the digit keys) ride the SAME seconds route on factory-owned sources (SV-H11): the decoder re-spawns at the target's seconds and lands with one pull instead of re-decoding every intervening frame, so the keyframe-snap trade-off applies to them too. A local GIF rides the same route but never the filesystem: it re-seeks inside the bytes captured at open (the single-capture law) and its converted-frame cache (SV-M40) serves any frame already painted, so seek round-trips cost zero re-reads and zero re-conversions, exactly frame index. Injected decoders that reopen from their own head (no seconds notion) keep the frame-exact forward walk, bounded by the per-tick budget. -
Audio pause/seek on Windows.
AudioPlayerno longer relies onSIGSTOP/SIGCONT(which are absent on Windows and unreliable under a PTY): pause terminates the subprocess and resume re-spawnsffplay/mpvfrom the banked playback position (-ss/--start). The trade-off is a short re-open latency on resume, and the audio clock is quantised to the last pause boundary rather than frame-exact. Rapid toggles are coalesced (SV-L87/087): a resume landing within 250 ms of the previous spawn defers to the next tick once the floor elapses, so keyboard-mashing costs at most one respawn per interval (a legitimate resume waits at most that floor). Nothing cheaper exists to use instead — the mute path was checked, not assumed: ffplay exposes no control channel to a stdin-less child and mpv spawns without an IPC socket, so mute-by-argument would itself respawn. -
Video decode via ffmpeg is refused on Windows. The frame pump drains ffmpeg's stdout with
stream_select(), which is documented-unsupported on Windows — a failed select answers "no data", so a Windows spawn would black-screen silently while the child kept producing frames nobody read (SV-M44, owner-gated route (a): loud refusal beats a silent lie).FfmpegDecoder::open()throws a guidance error there instead; GIF playback (pure-PHPGifDecoder) remains available on Windows, and mp4/avi/webm/stream sources play on Linux/macOS hosts. The blocking-read and file-sink pump reworks that would lift the refusal are open follow-ups gated on a Windows CI leg. -
Audio headers are forwarded, but only in the two dialects
ffplay/mpvunderstand. The request headers given toReel::openUrl()ride on ffmpeg's video input (-headers/-user_agent) and on the audio companion:ffplaygets the same-headersblob,mpvgets one--http-header-fields="Name: value"per pair (rendered byHttpHeaders::toMpvHeaderFields(), which includesUser-Agent, so mpv is never also given--user-agent). A header that neither child can be handed — a per-request nonce, or a cookie the video side obtained by redirect — still will not reach audio. On a signed or 403-gated stream audio therefore now authenticates the same way video does; a local path drops the headers altogether and logsheader.ignored_local_source.audio(with any credentials in the URL redacted) rather than sending credentials to a file. -
Decode is synchronous behind a per-tick budget.
next()reads the ffmpeg stdout pipe — non-blocking, behind a boundedstream_select()deadline — so a stalled network source surfaces as end-of-stream instead of hanging the loop. A tick that falls behind by many frames decodes the catch-up frames inline, but only within a budget:Player::open()now arms a default ofmax(50 ms, 2 × frame interval)(SV-M19), andReel::withFrameBudget($ms)threads a custom value through the build (remaining catch-up converges over subsequent ticks instead of blocking one — a long seek keeps painting while it catches up). Pass0.0to opt out into the old unbounded single-tick walk; hand-built entries (fromDecoder/openForTest) keep that unbounded default for parity fixtures. The budget is checked between frames, so it cannot preempt a single frame decode already in flight; per-read bounding comes from the pipe timeout.
Public API
The entry points worth knowing: Reel (open/openUrl/play/toPlayer + withMode/withAutoMode/withFps/withLoop/withRamp/withSize/withSubtitles/withAudio/withFrameBudget/withAllowedHosts/withHeaders/withCellPx + the removal doors withoutSubtitles/withoutHeaders/withoutRamp — the allowlist has no remover by design, a security field never loosens via absence), Player (open/fromDecoder + pause/play/stop/isStopped/withSeek/withSubtitles/withAudio/frameAt/seekToSeconds/canSeekByTime/position/duration), AudioPlayer (start/stop/pause/resume/mute/unmute/isMuted/isPlaying/hasStarted/position/exitCode), Synthetic::generate (path defaults to Synthetic::DEFAULT_PATH; the returned path is the source of truth — a refused target yields a private stand-in path), WebVtt::parse, VideoSource::probe, HttpHeaders::parse, Probe, DecoderFactory::new, and RendererFactory (auto/autoMode/supports/supportedModes/diagnose + support/canRender — the full-fold verdict as a SugarCraft\Video\Render\Support enum, refusal-is-data for embedding hosts). Two Probe classes share the short name: the roster entry here is SugarCraft\Video\Source\Probe (external-binary presence checks for ffmpeg/ffprobe/ffplay/mpv), while the auto-mode fallback above is SugarCraft\ColorProfile\Probe.
Ceilings that shape what plays: source capture is capped at 64 MiB per file (GifDecoder::MAX_SOURCE_BYTES, AnimatedWebpDecoder::MAX_SOURCE_BYTES); animated WebP at MAX_FRAMES 4096 frames, MAX_CANVAS_PIXELS 2048² per canvas and MAX_TOTAL_PIXELS 33,554,432 pixels summed across the file; GIF residency at an internal GifDecoder cap of 8,000,000 decoded pixels per playthrough; subtitles at 4 MiB (Reel::MAX_SUBTITLE_BYTES) and 10,000 cues (WebVtt::MAX_CUES, announced when truncated); the terminal geometry clamps to 10-200 columns and 5-80 rows (Player::MIN/MAX_COLS, MIN/MAX_ROWS). ffprobe output drains under an 8 MiB ceiling and a 10 s deadline; each ffmpeg frame read is bounded by a per-fill timeout.
Color and terminal honesty
The graphics ladder in RendererFactory::auto() descends sixel → kitty → iterm2 → halfblock → ansi256 → ascii: a TrueColor profile answers with the half-block rung when the terminal draws block glyphs safely, and with ANSI 256 when it cannot, so auto never selects truecolor or quarterblock — those are explicit modes only. The rung walk is a pure decision over the collected signals (RendererFactory::autoModeFrom()); supports() is the door for explicit modes and the mode cycle, where an unsupported choice raises a typed refusal naming the best mode for this seat; RendererFactory::support($mode, $cols, $rows) is the inspectable verdict for hosts — protocol claim, ext-gd, block-glyph safety and the SV-H7 cell window folded into one Support case (or canRender() for the boolean), so a consumer loop never re-derives the matrix. Graphics modes refuse loudly when the PHP lacks ext-gd — and the refuse runs
before any probe or decoder child is spawned, so a refused open leaks nothing
(SV-L66); an auto-resolved graphics seat on such a build steps down to the
next honest rung instead of throwing — refusals are for promises, not
guesses. NO_COLOR is honored transitively: sugar-colorprofile's probe (CLICOLOR_FORCE/FORCE_COLOR/NO_COLOR chain) reports reduced capability and the ladder steps down accordingly.
Localization
User-facing strings live in lang/en.php behind Lang::t(); English is the only locale shipped today, and unknown keys fall back to the raw key rather than crashing.