Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
307 changes: 104 additions & 203 deletions README.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions terminal_ascii_art/charsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ def get_charset(name: str = DEFAULT_CHARSET, *, invert: bool = False) -> str:


def brightness_to_index(brightness: float, ramp_length: int) -> int:
"""Map a brightness in the 0..255 range to a safe ramp index."""
"""Map a brightness in the 0..255 range to the nearest safe ramp index."""
if ramp_length < 1:
raise ValueError("A character ramp cannot be empty.")
value = max(0.0, min(255.0, float(brightness)))
return int(value * (ramp_length - 1) / 255.0)
return round(value * (ramp_length - 1) / 255.0)


def brightness_to_char(brightness: float, ramp: str) -> str:
Expand Down
18 changes: 16 additions & 2 deletions terminal_ascii_art/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ def _positive_float(value: str) -> float:
return parsed


def _nonnegative_float(value: str) -> float:
parsed = float(value)
if not math.isfinite(parsed) or parsed < 0:
raise argparse.ArgumentTypeError("must be a finite number zero or greater")
return parsed


def _unit_float(value: str) -> float:
parsed = float(value)
if not 0 <= parsed <= 1:
Expand Down Expand Up @@ -97,15 +104,15 @@ def build_parser() -> argparse.ArgumentParser:
action="store_false",
help=argparse.SUPPRESS,
)
video_parser.add_argument("--fps", type=_positive_float, default=20.0)
video_parser.add_argument("--fps", type=_positive_float, default=VideoOptions.fps)
video_parser.add_argument(
"--width", type=_positive_int, default=160, help="maximum character width"
)
video_parser.add_argument(
"--smoothing",
type=_unit_float,
default=1.0,
help="temporal smoothing: 1 is crisp, lower values add trails",
help="reduce shimmer in still areas: 1 disables blending, 0 is strongest",
)
video_parser.add_argument(
"--quant",
Expand All @@ -120,6 +127,12 @@ def build_parser() -> argparse.ArgumentParser:
help="maximum consecutive frames dropped to catch up",
)
video_parser.add_argument("--no-audio", action="store_true", help="disable FFplay audio")
video_parser.add_argument(
"--start-delay",
type=_nonnegative_float,
default=VideoOptions.start_delay,
help="wait before starting video and audio, in seconds (default: %(default)s)",
)
video_parser.add_argument(
"--audio-delay",
type=_audio_delay,
Expand Down Expand Up @@ -187,6 +200,7 @@ def _run_video(args: argparse.Namespace) -> int:
max_frame_skip=args.max_frame_skip,
audio=not args.no_audio,
audio_delay=args.audio_delay,
start_delay=args.start_delay,
)
play_video(
args.path.expanduser().resolve(),
Expand Down
25 changes: 19 additions & 6 deletions terminal_ascii_art/media/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,36 +21,49 @@ def get_image_dimensions(path: Path) -> tuple[int, int]:

try:
with Image.open(path) as image:
# EXIF orientations 5..8 rotate the displayed image by 90 degrees.
if image.getexif().get(274) in (5, 6, 7, 8):
return image.height, image.width
return image.size
except (OSError, ValueError) as exc:
raise ImageRenderError(f"Could not open image '{path}': {exc}") from exc


def render_image(path: Path, *, width: int, height: int, ramp: str) -> str:
try:
from PIL import Image
from PIL import Image, ImageFilter, ImageOps
except ImportError as exc:
raise ImageRenderError(
"Image rendering requires Pillow. Install the project dependencies first."
) from exc

if not path.is_file():
raise ImageRenderError(f"Image not found: {path}")
if width <= 0 or height <= 0:
raise ImageRenderError("Render dimensions must be positive.")
if not ramp:
raise ImageRenderError("A character ramp cannot be empty.")

try:
with Image.open(path) as source:
source = ImageOps.exif_transpose(source)
if "A" in source.getbands() or "transparency" in source.info:
# Match a blank background for both normal and inverted ramps.
background = 255 if ramp[-1] == " " else 0
matte = Image.new("RGBA", source.size, (background,) * 3 + (255,))
source = Image.alpha_composite(matte, source.convert("RGBA"))
grayscale = source.convert("L")
resampling = getattr(Image, "Resampling", Image).LANCZOS
resized = grayscale.resize((width, height), resampling)
if hasattr(resized, "get_flattened_data"):
pixels = list(resized.get_flattened_data())
else:
pixels = list(resized.getdata())
# Recover a little edge contrast lost when reducing to a tiny grid.
resized = resized.filter(ImageFilter.UnsharpMask(radius=0.6, percent=65, threshold=3))
pixels = resized.tobytes()
except (OSError, ValueError) as exc:
raise ImageRenderError(f"Could not render image '{path}': {exc}") from exc

palette = [brightness_to_char(value, ramp) for value in range(256)]
lines = []
for row_start in range(0, len(pixels), width):
row = pixels[row_start : row_start + width]
lines.append("".join(brightness_to_char(value, ramp) for value in row))
lines.append("".join(palette[value] for value in row))
return "\n".join(lines)
117 changes: 71 additions & 46 deletions terminal_ascii_art/media/video.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import math
import shutil
import subprocess
import time
Expand All @@ -18,14 +19,15 @@ class VideoRenderError(RuntimeError):

@dataclass(frozen=True)
class VideoOptions:
fps: float = 20.0
fps: float = 30.0
max_width: int = 160
color: bool = False
smoothing: float = 1.0
quantization: int = 4
max_frame_skip: int = 5
audio: bool = True
audio_delay: float = 0.0
start_delay: float = 0.0


def _load_numpy() -> Any:
Expand Down Expand Up @@ -83,50 +85,61 @@ def _frame_array(raw: bytes, rows: int, cols: int, color: bool, np: Any) -> Any:
return np.frombuffer(raw, dtype=np.uint8).reshape(shape).astype(np.float32)


def _smooth(current: Any, previous: Any | None, factor: float) -> Any:
def _smooth(current: Any, previous: Any | None, factor: float, np: Any) -> Any:
"""Blend small fluctuations, but keep moving edges and scene cuts crisp."""
if previous is None or factor >= 0.999:
return current
return previous + (current - previous) * factor
difference = np.abs(current - previous)
if current.ndim == 3:
difference = difference.max(axis=2, keepdims=True)
# A change of 32 levels or more uses the new pixel without a motion trail.
blend = factor + (1.0 - factor) * np.clip(difference / 32.0, 0.0, 1.0)
return previous + (current - previous) * blend


def _character_indices(brightness: Any, ramp: str, np: Any) -> Any:
"""Select the nearest shade instead of consistently rounding darker."""
return np.clip(
np.rint(brightness * (len(ramp) - 1) / 255), 0, len(ramp) - 1
).astype(np.intp)


def _render_mono(array: Any, ramp: str, np: Any) -> str:
indices = np.clip(
(array * (len(ramp) - 1) / 255).astype(np.int32), 0, len(ramp) - 1
)
return "\n".join("".join(ramp[index] for index in row) for row in indices.tolist())
indices = _character_indices(array, ramp, np)
characters = np.asarray(list(ramp))[indices]
return "\n".join("".join(row) for row in characters.tolist())


def _render_color(array: Any, ramp: str, quantization: int, np: Any) -> str:
brightness = 0.299 * array[..., 0] + 0.587 * array[..., 1] + 0.114 * array[..., 2]
char_indices = np.clip(
(brightness * (len(ramp) - 1) / 255).astype(np.int32), 0, len(ramp) - 1
)
char_indices = _character_indices(brightness, ramp, np)
characters = np.asarray(list(ramp))[char_indices]
clipped = np.clip(array, 0, 255)
if quantization > 1:
colors = (clipped // quantization * quantization).astype(np.int64)
colors = np.clip(np.rint(clipped / quantization) * quantization, 0, 255)
else:
colors = clipped.astype(np.int64)
colors = np.rint(clipped)
colors = colors.astype(np.uint32)

key = (
(colors[..., 0] << 40)
| (colors[..., 1] << 32)
| (colors[..., 2] << 24)
| char_indices.astype(np.int64)
)
# Changing a character does not require repeating the same ANSI color.
key = (colors[..., 0] << 16) | (colors[..., 1] << 8) | colors[..., 2]

lines = []
rows, cols = key.shape
for y in range(rows):
changes = np.flatnonzero(key[y, 1:] != key[y, :-1]) + 1
starts = np.concatenate(([0], changes))
ends = np.concatenate((changes, [cols]))
text = "".join(characters[y].tolist())
parts = []
for start, end in zip(starts.tolist(), ends.tolist()):
red, green, blue = colors[y, start]
character = ramp[char_indices[y, start]]
parts.append(
f"\033[38;2;{red};{green};{blue}m" + character * (end - start)
)
for start, end, (red, green, blue) in zip(
starts.tolist(), ends.tolist(), colors[y, starts].tolist()
):
run = text[start:end]
if run.strip():
parts.append(f"\033[38;2;{red};{green};{blue}m" + run)
else:
parts.append(run)
lines.append("".join(parts) + "\033[0m")
return "\n".join(lines)

Expand Down Expand Up @@ -161,6 +174,8 @@ def _stop_process(process: subprocess.Popen[Any] | None) -> None:


def play_video(video: Path, *, options: VideoOptions, ramp: str) -> None:
if not math.isfinite(options.start_delay) or options.start_delay < 0:
raise VideoRenderError("Start delay must be a finite number zero or greater.")
if not video.is_file():
raise VideoRenderError(f"Video not found: {video}")
if shutil.which("ffmpeg") is None:
Expand All @@ -179,7 +194,6 @@ def play_video(video: Path, *, options: VideoOptions, ramp: str) -> None:
print(f"Render: {cols} x {rows} characters at {options.fps:g} FPS")
print(f"Mode: {'ANSI true-color' if options.color else 'monochrome'}")
print(f"Audio: {'enabled' if options.audio else 'disabled'}")
print("Starting... Press Ctrl+C to stop.")

command = [
"ffmpeg",
Expand All @@ -189,7 +203,7 @@ def play_video(video: Path, *, options: VideoOptions, ramp: str) -> None:
"-i",
str(video),
"-vf",
f"fps={options.fps},scale={cols}:{rows}",
f"fps={options.fps},scale={cols}:{rows}:flags=lanczos+accurate_rnd:out_range=full",
"-f",
"rawvideo",
"-pix_fmt",
Expand All @@ -202,6 +216,13 @@ def play_video(video: Path, *, options: VideoOptions, ramp: str) -> None:
interrupted = False

try:
if options.start_delay > 0:
print(
f"Starting in {options.start_delay:g} seconds... Press Ctrl+C to cancel.",
flush=True,
)
time.sleep(options.start_delay)
print("Starting... Press Ctrl+C to stop.")
video_process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
Expand All @@ -211,17 +232,8 @@ def play_video(video: Path, *, options: VideoOptions, ramp: str) -> None:
if video_process.stdout is None:
raise VideoRenderError("FFmpeg did not provide a video stream.")

if options.audio and options.audio_delay <= 0:
audio_process = _start_audio(video)
if options.audio_delay < 0:
time.sleep(-options.audio_delay)

start_time = time.perf_counter()
audio_start_time = (
start_time + options.audio_delay
if options.audio and options.audio_delay > 0
else None
)
start_time = None
audio_start_time = None
frame_duration = 1.0 / options.fps
frame_index = 0
consecutive_drops = 0
Expand All @@ -233,29 +245,42 @@ def play_video(video: Path, *, options: VideoOptions, ramp: str) -> None:
if raw is None:
break

now = time.perf_counter()
if audio_start_time is not None and now >= audio_start_time:
audio_process = _start_audio(video)
audio_start_time = None
# Decoder startup is not playback lag. Start the clock and audio
# only once a complete first frame is available.
if start_time is None:
if options.audio and options.audio_delay <= 0:
audio_process = _start_audio(video)
if options.audio_delay < 0:
time.sleep(-options.audio_delay)
start_time = time.perf_counter()
if options.audio and options.audio_delay > 0:
audio_start_time = start_time + options.audio_delay

target_time = start_time + frame_index * frame_duration
frame_index += 1
lag = now - target_time
lag = time.perf_counter() - target_time
if lag > frame_duration and consecutive_drops < options.max_frame_skip:
consecutive_drops += 1
previous = None
continue

consecutive_drops = 0
if lag < 0:
time.sleep(-lag)

current = _frame_array(raw, rows, cols, options.color, np)
current = _smooth(current, previous, options.smoothing)
current = _smooth(current, previous, options.smoothing, np)
previous = current
if options.color:
frame = _render_color(current, ramp, options.quantization, np)
else:
frame = _render_mono(current, ramp, np)

# Prepare the frame before waiting so render cost does not add
# a variable delay to every scheduled presentation.
remaining = target_time - time.perf_counter()
if remaining > 0:
time.sleep(remaining)
if audio_start_time is not None and time.perf_counter() >= audio_start_time:
audio_process = _start_audio(video)
audio_start_time = None
draw_frame(frame)

video_process.wait(timeout=5)
Expand Down
2 changes: 1 addition & 1 deletion terminal_ascii_art/renderers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class Demo:
demo.name: demo
for demo in (
Demo("cube", "Rotating filled cube with lighting and depth buffering", 80, 0.44, cube.render_frame),
Demo("sphere", "Mathematically shaded rotating sphere", 80, 0.44, sphere.render_frame),
Demo("sphere", "Shaded sphere with an orbiting light", 80, 0.44, sphere.render_frame),
Demo("donut", "Parametric torus with lighting and depth buffering", 80, 0.44, donut.render_frame),
Demo("planet", "Procedural planet with terrain and atmospheric rim", 90, 0.42, planet.render_frame),
Demo("blackhole", "Stylized accretion disk, stars, and photon ring", 100, 0.42, blackhole.render_frame),
Expand Down
16 changes: 16 additions & 0 deletions terminal_ascii_art/renderers/common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
"""Small helpers shared by procedural renderers."""

import math

from terminal_ascii_art.charsets import brightness_to_index
from terminal_ascii_art.terminal import CHAR_ASPECT


def shade(unit_brightness: float, ramp: str) -> str:
Expand All @@ -10,3 +13,16 @@ def shade(unit_brightness: float, ramp: str) -> str:

def frame_to_text(buffer: list[list[str]]) -> str:
return "\n".join("".join(row) for row in buffer)


def sphere_point(
px: int, py: int, width: int, height: int
) -> tuple[float, float, float] | None:
"""Reconstruct a front-facing sphere with the terminal cell aspect ratio."""
radius = 0.9 * min(width / 2, height / (2 * CHAR_ASPECT))
x = (px + 0.5 - width / 2) / radius
y = (height / 2 - py - 0.5) / (radius * CHAR_ASPECT)
distance = x * x + y * y
if distance > 1:
return None
return x, y, -math.sqrt(1 - distance)
Loading
Loading