All 42 libraries

SugarVideo

Terminal video player

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

SugarVideo code coverage

Terminal video player — plays mp4, gif, avi, webm, animated webp on the fly, rendering each frame as ASCII, ANSI 256-color, truecolor half-/quarter-blocks, or via modern graphics protocols (sixel / kitty / iTerm2), with WebVTT subtitle overlays.

Install

composer require sugarcraft/sugar-video

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();

Rendering modes

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

Keyboard controls

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

Behavior (no keyboard shortcut)

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

What's in the box

Multi-format decodeffmpeg for mp4/avi/webm, pure-PHP + ext-gd for GIF and animated WebP (a RIFF container walk with per-frame GD decode). No external deps beyond the ffmpeg binaries for the video containers.
8 rendering modes + autoascii, ansi256, truecolor, half-block, quarter-block, sixel, kitty, iTerm2 — Player::open() and Reel default to resolving the terminal from its environment (a lookup table, no protocol negotiation) and picking the best available.
Auto terminal resizeSIGWINCH handler re-scales video to fit the new terminal dimensions without restarting playback.
Seek + speed controlKeyboard-driven seek (arrows, 0-9) and speed control ([ / ]) with frame-skip resync; ffmpeg input seeking (-ss before -i) for instant jumps on long streams.
WebVTT subtitlesReel::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.
AccessibilityThe caption line is the one real-text channel in every graphics mode — the text alternative for playback that image protocols render as silent pixels — with full keyboard control and nothing decided by a stray keystroke. Motion is never imposed: playback starts paused. The README Accessibility section carries the detail.
Reduced motionNothing auto-plays: Player::open() returns a paused model already showing one real poster frame, and Reel::play() waits for Space before any motion. A REDUCE_MOTION host is honored because no motion is ever unsolicited — there is no auto-play to suppress.
Audio companionAudioPlayer shells out to ffplay or mpv as the audio output companion (the Player keeps the master clock); pausing terminates and re-spawns the companion so no silent zombie burns CPU, and degrades gracefully when no audio track is present.
Remote sources with headersReel::openUrl() forwards an SSRF guard (allowedHosts; a bare URL logs a warning and allows any host) and redacts URL credentials from every log and error; request headers ride onto ffmpeg for signed CDN URLs, and audio re-presents the same headers.
Loop playbackReel::new()->withLoop(true)->play() loops from end back to start automatically.
Delta repaintOnly changed ROWS are re-rendered each frame unless the host opts into cell-granularity diffing (cellDiffRenderer), dramatically reducing output for static scenes.
SGR run-length coalescingOn the text rungs the Player composes frames inline (frameToBuffer()) and the cell buffer's ANSI writer emits color SGR codes only on color transitions, collapsing runs on static-ish scenes; the factory-built Ascii/HalfBlock/QuarterBlock renderers themselves are not reached by the Player runtime.

Source & demos

Try the quickstart →

API

API surface — classes, constructors, and methods.
ClassMethodDescription
Reel::open(path)Open a video file
Reel::openUrl(url, headers, allowedHosts)Open a remote stream behind the SSRF guard
Reel::new()Create an unbound reel — play() falls back to the synthetic test pattern, but toPlayer() refuses to embed one
ReelwithMode(Mode)Set rendering mode
ReelwithSize(cols, rows)Set terminal cell dimensions
ReelwithFps(?float)FPS override (null = auto-detect)
ReelwithLoop(bool)Enable/disable loop
ReelwithRamp(name)Select the ascii/ansi256 luminance ramp (minimal, standard, dense)
ReelwithSubtitles(path)Attach a WebVTT (or lenient SRT) caption track
ReelwithHeaders(headers)Attach/replace request headers for remote sources
ReelwithAllowedHosts(hosts)Pin the remote host allowlist
ReelwithCellPx(w, h)Tell the player the terminal cell pixel size (graphics modes rasterize at cols·w × rows·h)
ReelwithAutoMode()Switch to auto mode: the renderer ladder picks the best supported mode at open time
ReeltoPlayer()Build the Player (paused; source already opened — ffmpeg-routed sources spawn their ffmpeg child now, local GIF/animated-WebP decode in-process, the ffprobe child is transient)
Reelplay()Run the player
Player::open(videoPath, cellsW, cellsH, ?fpsOverride, ?Mode, loop, ramp, cellPxW, cellPxH, subtitles, headers, frameBudgetMs, ?autoModeChooser)Open a video source; a null Mode auto-detects terminal capability (the default)
Player::fromDecoder(decoder, cellsW, cellsH, fps, mode, …)Mount playback over any injected Decoder (server-transcoded streams, test doubles)
Player::openForTest(decoder, fps, totalFrames, cellsW, cellsH, …)Deprecated alias of ::fromDecoder() for HalfBlock test wiring
Player::withSubtitles(WebVtt)Attach a parsed subtitle track to the player
Player::seekToSeconds(sec)Seek to a timeline position in seconds
Player::position() / ::duration()Current playhead and total duration in seconds
WebVtt::parse(text)Parse a WebVTT (lenient SRT) track into cues; bounded at MAX_CUES
WebVttcueAt(seconds)Find the active caption for a timeline position: binary search for the rightmost start, then a back-walk bounded by MAX_CUES to the containing cue
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 (one header and global palette, NETSCAPE2.0 loop, a GCE on every frame and a local palette on each frame after the first, one trailer), so decoders read every frame; a 1×1 GIF stands in when ext-gd is absent. The path defaults to the public DEFAULT_PATH constant, and the returned path — not the argument — is the source of truth: a refused target (e.g. a planted symlink) 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

Demos.

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

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

Play

Synthetic rainbow-gradient GIF used by the playback demos.

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