curlcast 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- curlcast/__init__.py +20 -0
- curlcast/__main__.py +8 -0
- curlcast/audio.py +463 -0
- curlcast/cli.py +208 -0
- curlcast/demo.py +158 -0
- curlcast/ffmpeg.py +115 -0
- curlcast/player.py +383 -0
- curlcast/py.typed +0 -0
- curlcast/renderers/__init__.py +70 -0
- curlcast/renderers/_pixels.py +37 -0
- curlcast/renderers/ascii.py +114 -0
- curlcast/renderers/base.py +128 -0
- curlcast/renderers/blocks.py +138 -0
- curlcast/terminal.py +146 -0
- curlcast-0.1.0.dist-info/METADATA +411 -0
- curlcast-0.1.0.dist-info/RECORD +19 -0
- curlcast-0.1.0.dist-info/WHEEL +4 -0
- curlcast-0.1.0.dist-info/entry_points.txt +2 -0
- curlcast-0.1.0.dist-info/licenses/LICENSE +21 -0
curlcast/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""CurlCast — render photos, GIFs, and videos in crisp terminal art.
|
|
2
|
+
|
|
3
|
+
Public API surface
|
|
4
|
+
------------------
|
|
5
|
+
``curlcast.cli``
|
|
6
|
+
Typer command line interface (``view``, ``play``, ``demo``).
|
|
7
|
+
``curlcast.player``
|
|
8
|
+
Frame sources and the drift-corrected playback loop.
|
|
9
|
+
``curlcast.audio``
|
|
10
|
+
Cross-platform audio backends with an audio-master playback clock.
|
|
11
|
+
``curlcast.renderers``
|
|
12
|
+
Pluggable renderer strategy (``BaseRenderer`` → HD blocks / ASCII).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
__author__ = "CurlCast Contributors"
|
|
19
|
+
|
|
20
|
+
__all__ = ["__version__", "__author__"]
|
curlcast/__main__.py
ADDED
curlcast/audio.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
"""Cross-platform audio playback and the audio-master playback clock.
|
|
2
|
+
|
|
3
|
+
Backends, tried in order
|
|
4
|
+
------------------------
|
|
5
|
+
1. **sounddevice** (core dependency) — ffmpeg streams raw ``s16le`` PCM into a
|
|
6
|
+
PortAudio output stream. No temp files, no whole-track buffering, and
|
|
7
|
+
``Stream.time`` provides a sample-accurate clock, so video frames can be
|
|
8
|
+
paced to what the speaker is actually playing.
|
|
9
|
+
2. **ffplay** — used directly on the source file if it is on ``PATH``.
|
|
10
|
+
3. **mpv** — same, audio only.
|
|
11
|
+
4. **afplay** (macOS) — the audio track is extracted to a temp ``.m4a`` with
|
|
12
|
+
the bundled ffmpeg first; afplay cannot demux ``.mp4`` containers.
|
|
13
|
+
5. **silence** — one warning per process, video still plays.
|
|
14
|
+
|
|
15
|
+
Lifecycle
|
|
16
|
+
---------
|
|
17
|
+
:meth:`AudioManager.prepare` opens the output stream (PortAudio/WASAPI device
|
|
18
|
+
setup can take a moment) **without** starting playback. The player then decodes
|
|
19
|
+
its first frame and calls :meth:`AudioManager.start`, so audio and frame 1 begin
|
|
20
|
+
at the same instant and no frames are lost while the device initialises.
|
|
21
|
+
|
|
22
|
+
:meth:`AudioManager.position` is the media clock: with sounddevice it reports
|
|
23
|
+
the audible position (``stream.time - baseline - latency``); subprocess
|
|
24
|
+
backends fall back to a monotonic timer started when the process spawns.
|
|
25
|
+
Stopping is immediate and idempotent, so Ctrl+C never leaves sound behind.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import contextlib
|
|
31
|
+
import os
|
|
32
|
+
import platform
|
|
33
|
+
import shutil
|
|
34
|
+
import subprocess
|
|
35
|
+
import tempfile
|
|
36
|
+
import threading
|
|
37
|
+
import time
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
from typing import Any
|
|
40
|
+
|
|
41
|
+
from curlcast.ffmpeg import ffmpeg_exe
|
|
42
|
+
|
|
43
|
+
SAMPLE_RATE = 48_000
|
|
44
|
+
CHANNELS = 2
|
|
45
|
+
BYTES_PER_SAMPLE = 2
|
|
46
|
+
CHUNK_FRAMES = 1024
|
|
47
|
+
CHUNK_BYTES = CHUNK_FRAMES * CHANNELS * BYTES_PER_SAMPLE
|
|
48
|
+
|
|
49
|
+
_SD_STATE: bool | None = None
|
|
50
|
+
_WARNED = False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ---------------------------------------------------------------------------
|
|
54
|
+
# Backend discovery
|
|
55
|
+
# ---------------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _sounddevice_available() -> bool:
|
|
59
|
+
global _SD_STATE
|
|
60
|
+
if _SD_STATE is None:
|
|
61
|
+
try:
|
|
62
|
+
import sounddevice # noqa: F401
|
|
63
|
+
|
|
64
|
+
_SD_STATE = True
|
|
65
|
+
except Exception: # pragma: no cover - headless without PortAudio
|
|
66
|
+
_SD_STATE = False
|
|
67
|
+
return _SD_STATE
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _subprocess_candidates() -> list[str]:
|
|
71
|
+
names: list[str] = []
|
|
72
|
+
if shutil.which("ffplay"):
|
|
73
|
+
names.append("ffplay")
|
|
74
|
+
if shutil.which("mpv"):
|
|
75
|
+
names.append("mpv")
|
|
76
|
+
if platform.system() == "Darwin" and shutil.which("afplay"):
|
|
77
|
+
names.append("afplay")
|
|
78
|
+
return names
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def available_backends() -> list[str]:
|
|
82
|
+
"""Backends that could be used on this machine (for diagnostics)."""
|
|
83
|
+
names: list[str] = []
|
|
84
|
+
if _sounddevice_available():
|
|
85
|
+
names.append("sounddevice")
|
|
86
|
+
names.extend(_subprocess_candidates())
|
|
87
|
+
return names
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _warn_silent() -> None:
|
|
91
|
+
global _WARNED
|
|
92
|
+
if _WARNED:
|
|
93
|
+
return
|
|
94
|
+
_WARNED = True
|
|
95
|
+
from rich.console import Console
|
|
96
|
+
|
|
97
|
+
Console(stderr=True).print(
|
|
98
|
+
"[yellow]audio unavailable[/] — playing silently. "
|
|
99
|
+
"Install [bold]ffplay[/] or [bold]mpv[/] to enable sound."
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _terminate(proc: subprocess.Popen[Any]) -> None:
|
|
104
|
+
if proc.poll() is not None:
|
|
105
|
+
return
|
|
106
|
+
try:
|
|
107
|
+
proc.terminate()
|
|
108
|
+
proc.wait(timeout=1.0)
|
|
109
|
+
except Exception:
|
|
110
|
+
with contextlib.suppress(Exception): # already gone
|
|
111
|
+
proc.kill()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _spawn(cmd: list[str]) -> subprocess.Popen[Any] | None:
|
|
115
|
+
try:
|
|
116
|
+
return subprocess.Popen(
|
|
117
|
+
cmd,
|
|
118
|
+
stdin=subprocess.DEVNULL,
|
|
119
|
+
stdout=subprocess.DEVNULL,
|
|
120
|
+
stderr=subprocess.DEVNULL,
|
|
121
|
+
)
|
|
122
|
+
except (FileNotFoundError, OSError):
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# ---------------------------------------------------------------------------
|
|
127
|
+
# Audio manager
|
|
128
|
+
# ---------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class AudioManager:
|
|
132
|
+
"""Owns one audio backend for one playback pass.
|
|
133
|
+
|
|
134
|
+
The object doubles as the playback clock: call :meth:`prepare`, then
|
|
135
|
+
:meth:`start` just before the first frame, and poll :meth:`position` from
|
|
136
|
+
the render loop.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(self, source: Path, *, muted: bool = False, has_audio: bool = True) -> None:
|
|
140
|
+
self._source = Path(source)
|
|
141
|
+
self._muted = muted or not has_audio
|
|
142
|
+
self._backend = "none"
|
|
143
|
+
self._stream: Any = None
|
|
144
|
+
self._stream_base = 0.0
|
|
145
|
+
self._proc: subprocess.Popen[Any] | None = None
|
|
146
|
+
self._thread: threading.Thread | None = None
|
|
147
|
+
self._stop = threading.Event()
|
|
148
|
+
self._started_at: float | None = None
|
|
149
|
+
self._temp_path: Path | None = None
|
|
150
|
+
self._prepared = False
|
|
151
|
+
self._seek = 0.0
|
|
152
|
+
self._fallbacks: list[str] = []
|
|
153
|
+
|
|
154
|
+
# ------------------------------------------------------------------
|
|
155
|
+
@property
|
|
156
|
+
def backend(self) -> str:
|
|
157
|
+
return self._backend
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def muted(self) -> bool:
|
|
161
|
+
return self._muted
|
|
162
|
+
|
|
163
|
+
# ------------------------------------------------------------------
|
|
164
|
+
def prepare(self, seek: float = 0.0) -> None:
|
|
165
|
+
"""Open the preferred backend without starting playback.
|
|
166
|
+
|
|
167
|
+
Safe to call without :meth:`start`; :meth:`stop` releases everything.
|
|
168
|
+
"""
|
|
169
|
+
self.stop()
|
|
170
|
+
self._stop.clear()
|
|
171
|
+
self._seek = max(float(seek), 0.0)
|
|
172
|
+
self._prepared = True
|
|
173
|
+
|
|
174
|
+
if self._muted:
|
|
175
|
+
self._backend = "muted"
|
|
176
|
+
return
|
|
177
|
+
|
|
178
|
+
if _sounddevice_available() and self._open_sounddevice():
|
|
179
|
+
self._backend = "sounddevice"
|
|
180
|
+
return
|
|
181
|
+
|
|
182
|
+
self._backend = "none"
|
|
183
|
+
self._fallbacks = _subprocess_candidates()
|
|
184
|
+
|
|
185
|
+
def start(self, seek: float | None = None) -> None:
|
|
186
|
+
"""Begin playback and the media clock."""
|
|
187
|
+
if not self._prepared:
|
|
188
|
+
self.prepare(seek if seek is not None else 0.0)
|
|
189
|
+
elif seek is not None:
|
|
190
|
+
self._seek = max(float(seek), 0.0)
|
|
191
|
+
|
|
192
|
+
if self._backend == "sounddevice":
|
|
193
|
+
if self._begin_sounddevice():
|
|
194
|
+
return
|
|
195
|
+
self._backend = "none"
|
|
196
|
+
self._fallbacks = _subprocess_candidates()
|
|
197
|
+
|
|
198
|
+
if self._backend == "muted":
|
|
199
|
+
self._started_at = time.perf_counter()
|
|
200
|
+
return
|
|
201
|
+
|
|
202
|
+
if self._backend == "none":
|
|
203
|
+
if self._fallbacks:
|
|
204
|
+
self._backend = self._fallbacks.pop(0)
|
|
205
|
+
else:
|
|
206
|
+
self._started_at = time.perf_counter()
|
|
207
|
+
self._warn_once_if_needed()
|
|
208
|
+
return
|
|
209
|
+
|
|
210
|
+
# A subprocess backend is selected; try it, then the remaining ones.
|
|
211
|
+
while self._backend != "none":
|
|
212
|
+
backend = self._backend
|
|
213
|
+
self._backend = "none"
|
|
214
|
+
if self._start_subprocess(backend):
|
|
215
|
+
return
|
|
216
|
+
if not self._fallbacks:
|
|
217
|
+
break
|
|
218
|
+
self._backend = self._fallbacks.pop(0)
|
|
219
|
+
|
|
220
|
+
self._started_at = time.perf_counter()
|
|
221
|
+
self._warn_once_if_needed()
|
|
222
|
+
|
|
223
|
+
def position(self) -> float:
|
|
224
|
+
"""Seconds of media time elapsed at the speaker (or wall clock)."""
|
|
225
|
+
if self._backend == "sounddevice" and self._stream is not None:
|
|
226
|
+
try:
|
|
227
|
+
elapsed = float(self._stream.time) - self._stream_base
|
|
228
|
+
return max(0.0, elapsed - float(self._stream.latency))
|
|
229
|
+
except Exception: # pragma: no cover - stream closed mid-call
|
|
230
|
+
pass
|
|
231
|
+
if self._started_at is None:
|
|
232
|
+
return 0.0
|
|
233
|
+
return max(0.0, time.perf_counter() - self._started_at)
|
|
234
|
+
|
|
235
|
+
def stop(self) -> None:
|
|
236
|
+
"""Stop audio immediately; safe to call repeatedly."""
|
|
237
|
+
self._stop.set()
|
|
238
|
+
|
|
239
|
+
stream, self._stream = self._stream, None
|
|
240
|
+
if stream is not None:
|
|
241
|
+
try:
|
|
242
|
+
stream.abort(ignore_errors=True)
|
|
243
|
+
stream.close(ignore_errors=True)
|
|
244
|
+
except Exception: # pragma: no cover
|
|
245
|
+
pass
|
|
246
|
+
|
|
247
|
+
proc, self._proc = self._proc, None
|
|
248
|
+
if proc is not None:
|
|
249
|
+
_terminate(proc)
|
|
250
|
+
|
|
251
|
+
thread, self._thread = self._thread, None
|
|
252
|
+
if thread is not None and thread is not threading.current_thread():
|
|
253
|
+
thread.join(timeout=1.5)
|
|
254
|
+
|
|
255
|
+
temp_path, self._temp_path = self._temp_path, None
|
|
256
|
+
if temp_path is not None:
|
|
257
|
+
with contextlib.suppress(OSError): # Windows may still hold the file
|
|
258
|
+
temp_path.unlink(missing_ok=True)
|
|
259
|
+
|
|
260
|
+
self._started_at = None
|
|
261
|
+
self._stream_base = 0.0
|
|
262
|
+
self._prepared = False
|
|
263
|
+
self._fallbacks = []
|
|
264
|
+
|
|
265
|
+
# ------------------------------------------------------------------
|
|
266
|
+
# sounddevice backend
|
|
267
|
+
# ------------------------------------------------------------------
|
|
268
|
+
def _open_sounddevice(self) -> bool:
|
|
269
|
+
"""Spawn ffmpeg and open a PortAudio stream (not started yet)."""
|
|
270
|
+
try:
|
|
271
|
+
import sounddevice as sd
|
|
272
|
+
except Exception: # pragma: no cover
|
|
273
|
+
return False
|
|
274
|
+
|
|
275
|
+
cmd = [
|
|
276
|
+
ffmpeg_exe(),
|
|
277
|
+
"-hide_banner",
|
|
278
|
+
"-loglevel",
|
|
279
|
+
"error",
|
|
280
|
+
"-nostdin",
|
|
281
|
+
"-ss",
|
|
282
|
+
f"{self._seek:.3f}",
|
|
283
|
+
"-i",
|
|
284
|
+
str(self._source),
|
|
285
|
+
"-vn",
|
|
286
|
+
"-sn",
|
|
287
|
+
"-dn",
|
|
288
|
+
"-f",
|
|
289
|
+
"s16le",
|
|
290
|
+
"-acodec",
|
|
291
|
+
"pcm_s16le",
|
|
292
|
+
"-ar",
|
|
293
|
+
str(SAMPLE_RATE),
|
|
294
|
+
"-ac",
|
|
295
|
+
str(CHANNELS),
|
|
296
|
+
"-",
|
|
297
|
+
]
|
|
298
|
+
try:
|
|
299
|
+
proc = subprocess.Popen(
|
|
300
|
+
cmd,
|
|
301
|
+
stdin=subprocess.DEVNULL,
|
|
302
|
+
stdout=subprocess.PIPE,
|
|
303
|
+
stderr=subprocess.DEVNULL,
|
|
304
|
+
)
|
|
305
|
+
except (FileNotFoundError, OSError):
|
|
306
|
+
return False
|
|
307
|
+
assert proc.stdout is not None
|
|
308
|
+
|
|
309
|
+
stream = None
|
|
310
|
+
for latency in ("low", None):
|
|
311
|
+
try:
|
|
312
|
+
stream = sd.RawOutputStream(
|
|
313
|
+
samplerate=SAMPLE_RATE,
|
|
314
|
+
channels=CHANNELS,
|
|
315
|
+
dtype="int16",
|
|
316
|
+
blocksize=CHUNK_FRAMES,
|
|
317
|
+
latency=latency,
|
|
318
|
+
)
|
|
319
|
+
break
|
|
320
|
+
except Exception:
|
|
321
|
+
stream = None
|
|
322
|
+
if stream is None:
|
|
323
|
+
_terminate(proc)
|
|
324
|
+
return False
|
|
325
|
+
|
|
326
|
+
self._proc = proc
|
|
327
|
+
self._stream = stream
|
|
328
|
+
return True
|
|
329
|
+
|
|
330
|
+
def _begin_sounddevice(self) -> bool:
|
|
331
|
+
proc, stream = self._proc, self._stream
|
|
332
|
+
if proc is None or stream is None:
|
|
333
|
+
return False
|
|
334
|
+
try:
|
|
335
|
+
stream.start()
|
|
336
|
+
# PortAudio reports a device clock (not seconds since start) on
|
|
337
|
+
# several host APIs, so keep the baseline and subtract it.
|
|
338
|
+
self._stream_base = float(stream.time)
|
|
339
|
+
except Exception:
|
|
340
|
+
proc, self._proc = self._proc, None
|
|
341
|
+
if proc is not None:
|
|
342
|
+
_terminate(proc)
|
|
343
|
+
with contextlib.suppress(Exception):
|
|
344
|
+
stream.close(ignore_errors=True)
|
|
345
|
+
self._stream = None
|
|
346
|
+
return False
|
|
347
|
+
|
|
348
|
+
stop = self._stop
|
|
349
|
+
frame_bytes = CHANNELS * BYTES_PER_SAMPLE
|
|
350
|
+
|
|
351
|
+
def feed() -> None:
|
|
352
|
+
stdout = proc.stdout
|
|
353
|
+
assert stdout is not None
|
|
354
|
+
try:
|
|
355
|
+
while not stop.is_set():
|
|
356
|
+
chunk = stdout.read(CHUNK_BYTES)
|
|
357
|
+
if not chunk:
|
|
358
|
+
break
|
|
359
|
+
if len(chunk) % frame_bytes:
|
|
360
|
+
break
|
|
361
|
+
stream.write(chunk)
|
|
362
|
+
except Exception:
|
|
363
|
+
# Stream aborted or ffmpeg died - both normal on stop.
|
|
364
|
+
pass
|
|
365
|
+
|
|
366
|
+
self._thread = threading.Thread(target=feed, name="curlcast-audio", daemon=True)
|
|
367
|
+
self._thread.start()
|
|
368
|
+
self._started_at = time.perf_counter()
|
|
369
|
+
return True
|
|
370
|
+
|
|
371
|
+
# ------------------------------------------------------------------
|
|
372
|
+
# Subprocess backends
|
|
373
|
+
# ------------------------------------------------------------------
|
|
374
|
+
def _start_subprocess(self, backend: str) -> bool:
|
|
375
|
+
started = self._start_afplay() if backend == "afplay" else self._start_player(backend)
|
|
376
|
+
if started:
|
|
377
|
+
self._backend = backend
|
|
378
|
+
self._started_at = time.perf_counter()
|
|
379
|
+
return started
|
|
380
|
+
|
|
381
|
+
def _start_player(self, backend: str) -> bool:
|
|
382
|
+
if backend == "ffplay":
|
|
383
|
+
cmd = [
|
|
384
|
+
"ffplay",
|
|
385
|
+
"-nodisp",
|
|
386
|
+
"-autoexit",
|
|
387
|
+
"-loglevel",
|
|
388
|
+
"error",
|
|
389
|
+
"-ss",
|
|
390
|
+
f"{self._seek:.3f}",
|
|
391
|
+
"-i",
|
|
392
|
+
str(self._source),
|
|
393
|
+
]
|
|
394
|
+
else:
|
|
395
|
+
cmd = [
|
|
396
|
+
"mpv",
|
|
397
|
+
"--no-video",
|
|
398
|
+
"--really-quiet",
|
|
399
|
+
"--no-terminal",
|
|
400
|
+
f"--start={self._seek:.3f}",
|
|
401
|
+
str(self._source),
|
|
402
|
+
]
|
|
403
|
+
proc = _spawn(cmd)
|
|
404
|
+
if proc is None:
|
|
405
|
+
return False
|
|
406
|
+
time.sleep(0.05) # let obviously-broken invocations exit early
|
|
407
|
+
if proc.poll() is not None:
|
|
408
|
+
return False
|
|
409
|
+
self._proc = proc
|
|
410
|
+
return True
|
|
411
|
+
|
|
412
|
+
def _start_afplay(self) -> bool:
|
|
413
|
+
handle, name = tempfile.mkstemp(prefix="curlcast-", suffix=".m4a")
|
|
414
|
+
os.close(handle)
|
|
415
|
+
temp_path = Path(name)
|
|
416
|
+
cmd = [
|
|
417
|
+
ffmpeg_exe(),
|
|
418
|
+
"-y",
|
|
419
|
+
"-hide_banner",
|
|
420
|
+
"-loglevel",
|
|
421
|
+
"error",
|
|
422
|
+
"-nostdin",
|
|
423
|
+
"-i",
|
|
424
|
+
str(self._source),
|
|
425
|
+
"-vn",
|
|
426
|
+
"-ac",
|
|
427
|
+
"2",
|
|
428
|
+
"-ar",
|
|
429
|
+
"44100",
|
|
430
|
+
"-c:a",
|
|
431
|
+
"aac",
|
|
432
|
+
"-b:a",
|
|
433
|
+
"192k",
|
|
434
|
+
str(temp_path),
|
|
435
|
+
]
|
|
436
|
+
try:
|
|
437
|
+
completed = subprocess.run(
|
|
438
|
+
cmd,
|
|
439
|
+
stdin=subprocess.DEVNULL,
|
|
440
|
+
stdout=subprocess.DEVNULL,
|
|
441
|
+
stderr=subprocess.DEVNULL,
|
|
442
|
+
check=False,
|
|
443
|
+
)
|
|
444
|
+
except OSError:
|
|
445
|
+
temp_path.unlink(missing_ok=True)
|
|
446
|
+
return False
|
|
447
|
+
if completed.returncode != 0 or not temp_path.exists():
|
|
448
|
+
temp_path.unlink(missing_ok=True)
|
|
449
|
+
return False
|
|
450
|
+
|
|
451
|
+
proc = _spawn(["afplay", str(temp_path)])
|
|
452
|
+
if proc is None:
|
|
453
|
+
temp_path.unlink(missing_ok=True)
|
|
454
|
+
return False
|
|
455
|
+
self._temp_path = temp_path
|
|
456
|
+
self._proc = proc
|
|
457
|
+
return True
|
|
458
|
+
|
|
459
|
+
# ------------------------------------------------------------------
|
|
460
|
+
def _warn_once_if_needed(self) -> None:
|
|
461
|
+
# Silence is expected for GIFs and files without an audio stream.
|
|
462
|
+
if not self._muted:
|
|
463
|
+
_warn_silent()
|
curlcast/cli.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Typer command line interface.
|
|
2
|
+
|
|
3
|
+
Commands
|
|
4
|
+
--------
|
|
5
|
+
``curlcast view IMAGE``
|
|
6
|
+
Render a static image and exit.
|
|
7
|
+
``curlcast play MEDIA``
|
|
8
|
+
Play a video or GIF with synced audio.
|
|
9
|
+
``curlcast demo``
|
|
10
|
+
Run the built-in NumPy animation (no media file required).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import typer
|
|
20
|
+
from PIL import Image, ImageOps
|
|
21
|
+
from rich.console import Console
|
|
22
|
+
|
|
23
|
+
from curlcast import __version__
|
|
24
|
+
from curlcast.demo import DemoAnimation, run_demo
|
|
25
|
+
from curlcast.renderers import RenderMode, get_renderer
|
|
26
|
+
from curlcast.terminal import configure_streams
|
|
27
|
+
|
|
28
|
+
_IMAGES = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tif", ".tiff"}
|
|
29
|
+
_MEDIA = {".mp4", ".mov", ".webm", ".mkv", ".gif", ".avi", ".m4v"}
|
|
30
|
+
|
|
31
|
+
app = typer.Typer(
|
|
32
|
+
name="curlcast",
|
|
33
|
+
help=(
|
|
34
|
+
"Render photos, GIFs, and videos in crisp terminal art — with synced audio.\n\n"
|
|
35
|
+
"[bold]Examples[/]\n\n"
|
|
36
|
+
" curlcast view photo.jpg --mode ascii\n\n"
|
|
37
|
+
" curlcast play video.mp4 --loop\n\n"
|
|
38
|
+
" curlcast demo --animation torus"
|
|
39
|
+
),
|
|
40
|
+
add_completion=False,
|
|
41
|
+
rich_markup_mode="rich",
|
|
42
|
+
pretty_exceptions_show_locals=False,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
err = Console(stderr=True)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ---------------------------------------------------------------------------
|
|
49
|
+
# Shared helpers
|
|
50
|
+
# ---------------------------------------------------------------------------
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _require_file(path: Path, allowed: set[str]) -> None:
|
|
54
|
+
if not path.exists():
|
|
55
|
+
err.print(f"[red]error[/] file not found: [bold]{path}[/]")
|
|
56
|
+
raise typer.Exit(code=1)
|
|
57
|
+
if not path.is_file():
|
|
58
|
+
err.print(f"[red]error[/] not a file: [bold]{path}[/]")
|
|
59
|
+
raise typer.Exit(code=1)
|
|
60
|
+
suffix = path.suffix.lower()
|
|
61
|
+
if suffix not in allowed:
|
|
62
|
+
supported = ", ".join(sorted(allowed))
|
|
63
|
+
err.print(
|
|
64
|
+
f"[red]error[/] unsupported file type [bold]{suffix or '(none)'}[/]\n"
|
|
65
|
+
f" supported: {supported}"
|
|
66
|
+
)
|
|
67
|
+
raise typer.Exit(code=1)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _renderer(mode: RenderMode, width: int, no_color: bool):
|
|
71
|
+
try:
|
|
72
|
+
return get_renderer(mode, width=width, color=not no_color)
|
|
73
|
+
except ValueError as exc: # pragma: no cover - Typer validates the enum
|
|
74
|
+
err.print(f"[red]error[/] {exc}")
|
|
75
|
+
raise typer.Exit(code=1) from exc
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# ---------------------------------------------------------------------------
|
|
79
|
+
# Commands
|
|
80
|
+
# ---------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@app.command()
|
|
84
|
+
def view(
|
|
85
|
+
image_path: Path = typer.Argument(..., metavar="IMAGE", help="Image file to render."),
|
|
86
|
+
mode: RenderMode = typer.Option(
|
|
87
|
+
RenderMode.HD, "--mode", "-m", help="Render mode.", case_sensitive=False
|
|
88
|
+
),
|
|
89
|
+
width: int = typer.Option(
|
|
90
|
+
0, "--width", "-w", min=0, help="Output width in columns (0 = fit terminal)."
|
|
91
|
+
),
|
|
92
|
+
no_color: bool = typer.Option(False, "--no-color", help="Monochrome output."),
|
|
93
|
+
no_upscale: bool = typer.Option(
|
|
94
|
+
False, "--no-upscale", help="Never enlarge images smaller than the terminal."
|
|
95
|
+
),
|
|
96
|
+
) -> None:
|
|
97
|
+
"""Render a static image in the terminal and exit."""
|
|
98
|
+
_require_file(image_path, _IMAGES)
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
with Image.open(image_path) as opened:
|
|
102
|
+
image = ImageOps.exif_transpose(opened).convert("RGB")
|
|
103
|
+
image.load()
|
|
104
|
+
except (OSError, ValueError) as exc:
|
|
105
|
+
err.print(f"[red]error[/] cannot read image: {exc}")
|
|
106
|
+
raise typer.Exit(code=1) from exc
|
|
107
|
+
|
|
108
|
+
renderer = _renderer(mode, width, no_color)
|
|
109
|
+
art = renderer.render_image(image, upscale=not no_upscale)
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
sys.stdout.write(art + "\n")
|
|
113
|
+
sys.stdout.flush()
|
|
114
|
+
except BrokenPipeError:
|
|
115
|
+
raise typer.Exit(code=0) from None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@app.command()
|
|
119
|
+
def play(
|
|
120
|
+
media_path: Path = typer.Argument(..., metavar="MEDIA", help="Video or GIF to play."),
|
|
121
|
+
mode: RenderMode = typer.Option(
|
|
122
|
+
RenderMode.HD, "--mode", "-m", help="Render mode.", case_sensitive=False
|
|
123
|
+
),
|
|
124
|
+
width: int = typer.Option(
|
|
125
|
+
0, "--width", "-w", min=0, help="Output width in columns (0 = fit terminal)."
|
|
126
|
+
),
|
|
127
|
+
fps: float = typer.Option(
|
|
128
|
+
20.0, "--fps", min=1.0, max=120.0, help="Target frame rate (capped at source fps)."
|
|
129
|
+
),
|
|
130
|
+
loop: bool = typer.Option(False, "--loop", "-l", help="Loop until interrupted."),
|
|
131
|
+
no_audio: bool = typer.Option(False, "--no-audio", help="Disable audio playback."),
|
|
132
|
+
no_color: bool = typer.Option(False, "--no-color", help="Monochrome output."),
|
|
133
|
+
) -> None:
|
|
134
|
+
"""Play a video or GIF in the terminal with synced audio."""
|
|
135
|
+
_require_file(media_path, _MEDIA)
|
|
136
|
+
|
|
137
|
+
renderer = _renderer(mode, width, no_color)
|
|
138
|
+
|
|
139
|
+
from curlcast.ffmpeg import MediaError
|
|
140
|
+
from curlcast.player import play as play_media
|
|
141
|
+
|
|
142
|
+
try:
|
|
143
|
+
play_media(media_path, renderer, fps=fps, loop=loop, muted=no_audio)
|
|
144
|
+
except MediaError as exc:
|
|
145
|
+
err.print(f"[red]error[/] {exc}")
|
|
146
|
+
raise typer.Exit(code=1) from exc
|
|
147
|
+
except KeyboardInterrupt:
|
|
148
|
+
# Screen.__exit__ has already restored the cursor.
|
|
149
|
+
raise typer.Exit(code=130) from None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@app.command()
|
|
153
|
+
def demo(
|
|
154
|
+
mode: RenderMode = typer.Option(
|
|
155
|
+
RenderMode.HD, "--mode", "-m", help="Render mode.", case_sensitive=False
|
|
156
|
+
),
|
|
157
|
+
width: int = typer.Option(
|
|
158
|
+
0, "--width", "-w", min=0, help="Output width in columns (0 = fit terminal)."
|
|
159
|
+
),
|
|
160
|
+
duration: float = typer.Option(
|
|
161
|
+
10.0, "--duration", "-d", min=0.0, help="Demo length in seconds (0 = forever)."
|
|
162
|
+
),
|
|
163
|
+
fps: float = typer.Option(24.0, "--fps", min=1.0, max=60.0, help="Animation frame rate."),
|
|
164
|
+
animation: DemoAnimation = typer.Option(
|
|
165
|
+
DemoAnimation.PLASMA, "--animation", "-a", help="Animation to display."
|
|
166
|
+
),
|
|
167
|
+
no_color: bool = typer.Option(False, "--no-color", help="Monochrome output."),
|
|
168
|
+
) -> None:
|
|
169
|
+
"""Run a self-contained NumPy animation (no media file required)."""
|
|
170
|
+
renderer = _renderer(mode, width, no_color)
|
|
171
|
+
with contextlib.suppress(KeyboardInterrupt):
|
|
172
|
+
run_demo(renderer, duration=duration, fps=fps, animation=animation)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
# ---------------------------------------------------------------------------
|
|
176
|
+
# Root callback / entry point
|
|
177
|
+
# ---------------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@app.callback(invoke_without_command=True)
|
|
181
|
+
def _root(
|
|
182
|
+
ctx: typer.Context,
|
|
183
|
+
version: bool = typer.Option(
|
|
184
|
+
False,
|
|
185
|
+
"--version",
|
|
186
|
+
"-V",
|
|
187
|
+
help="Show the version and exit.",
|
|
188
|
+
is_eager=True,
|
|
189
|
+
),
|
|
190
|
+
) -> None:
|
|
191
|
+
"""CurlCast — terminal media player."""
|
|
192
|
+
configure_streams()
|
|
193
|
+
if version:
|
|
194
|
+
typer.echo(f"curlcast {__version__}")
|
|
195
|
+
raise typer.Exit()
|
|
196
|
+
if ctx.invoked_subcommand is None:
|
|
197
|
+
typer.echo(ctx.get_help())
|
|
198
|
+
raise typer.Exit()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def main() -> None:
|
|
202
|
+
"""Console-script entry point."""
|
|
203
|
+
configure_streams()
|
|
204
|
+
app()
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
if __name__ == "__main__": # pragma: no cover
|
|
208
|
+
main()
|