terminal-pixel-animation 0.3.5

Render pixel images as Unicode characters (Braille / Half-block) in the terminal with True Color support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import { useState, useEffect, useRef, useCallback } from "react";
import { WasmProvider, useBraille, useHalfBlock } from "terminal-pixel-animation-react";

// ── Pixel capture hook ───────────────────────────────────────────────────────

function useVideoFrames(videoRef: React.RefObject<HTMLVideoElement | null>) {
  const [pixels, setPixels] = useState<Uint8Array | null>(null);
  const [size, setSize] = useState({ w: 0, h: 0 });
  const offscreenRef = useRef<HTMLCanvasElement | null>(null);
  const ctxRef = useRef<CanvasRenderingContext2D | null>(null);

  useEffect(() => {
    const canvas = document.createElement("canvas");
    offscreenRef.current = canvas;
    ctxRef.current = canvas.getContext("2d", { willReadFrequently: true });
    return () => {
      offscreenRef.current = null;
      ctxRef.current = null;
    };
  }, []);

  const capture = useCallback(() => {
    const video = videoRef.current;
    const off = offscreenRef.current;
    const ctx = ctxRef.current;
    if (!video || !off || !ctx || video.readyState < 2) return;

    const vw = video.videoWidth;
    const vh = video.videoHeight;
    if (off.width !== vw || off.height !== vh) {
      off.width = vw;
      off.height = vh;
    }

    ctx.drawImage(video, 0, 0, vw, vh);
    const imageData = ctx.getImageData(0, 0, vw, vh);

    const rgb = new Uint8Array(vw * vh * 3);
    for (let i = 0, j = 0; i < imageData.data.length; i += 4, j += 3) {
      rgb[j] = imageData.data[i];
      rgb[j + 1] = imageData.data[i + 1];
      rgb[j + 2] = imageData.data[i + 2];
    }

    setPixels(rgb);
    setSize({ w: vw, h: vh });
  }, [videoRef]);

  return { pixels, size, capture };
}

// ── FPS counter hook ─────────────────────────────────────────────────────────

function useFps() {
  const [fps, setFps] = useState(0);
  const countRef = useRef(0);
  const lastRef = useRef(performance.now());

  const tick = useCallback(() => {
    countRef.current++;
    const now = performance.now();
    if (now - lastRef.current >= 1000) {
      setFps(countRef.current);
      countRef.current = 0;
      lastRef.current = now;
    }
  }, []);

  return { fps, tick };
}

// ── Braille renderer ─────────────────────────────────────────────────────────

function BrailleCanvas({ pixels, width, height, cols, rows }: {
  pixels: Uint8Array; width: number; height: number; cols: number; rows: number;
}) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const { decoded, error } = useBraille(pixels, width, height, cols, rows);
  const { fps, tick } = useFps();

  useEffect(() => {
    if (!decoded || !canvasRef.current) return;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d")!;

    const cellW = 8;
    const cellH = 14;
    canvas.width = cols * cellW;
    canvas.height = rows * cellH;

    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.font = `${cellH}px monospace`;
    ctx.textBaseline = "top";

    for (let i = 0; i < decoded.length; i++) {
      const cell = decoded[i];
      const col = i % cols;
      const row = Math.floor(i / cols);
      if (cell.char !== "\0" && cell.char !== " ") {
        ctx.fillStyle = `rgb(${cell.r},${cell.g},${cell.b})`;
        ctx.fillText(cell.char, col * cellW, row * cellH);
      }
    }

    tick();
  }, [decoded, cols, rows, tick]);

  if (error) return <p style={{ color: "red" }}>Error: {error.message}</p>;

  return (
    <div>
      <div style={{ marginBottom: 8, fontSize: 12, color: "#888" }}>
        Braille {cols}x{rows} | FPS: {fps}
      </div>
      <canvas ref={canvasRef} style={{ imageRendering: "pixelated", background: "#000" }} />
    </div>
  );
}

// ── Half-block renderer ──────────────────────────────────────────────────────

function HalfBlockCanvas({ pixels, width, height, cols, rows }: {
  pixels: Uint8Array; width: number; height: number; cols: number; rows: number;
}) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const { decoded, error } = useHalfBlock(pixels, width, height, cols, rows);
  const { fps, tick } = useFps();

  useEffect(() => {
    if (!decoded || !canvasRef.current) return;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext("2d")!;

    const px = 8;
    canvas.width = cols * px;
    canvas.height = rows * px;

    for (let i = 0; i < decoded.length; i++) {
      const cell = decoded[i];
      const col = i % cols;
      const row = Math.floor(i / cols);

      ctx.fillStyle = `rgb(${cell.rFg},${cell.gFg},${cell.bFg})`;
      ctx.fillRect(col * px, row * px, px, px / 2);
      ctx.fillStyle = `rgb(${cell.rBg},${cell.gBg},${cell.bBg})`;
      ctx.fillRect(col * px, row * px + px / 2, px, px / 2);
    }

    tick();
  }, [decoded, cols, rows, tick]);

  if (error) return <p style={{ color: "red" }}>Error: {error.message}</p>;

  return (
    <div>
      <div style={{ marginBottom: 8, fontSize: 12, color: "#888" }}>
        Half-block {cols}x{rows} | FPS: {fps}
      </div>
      <canvas ref={canvasRef} style={{ imageRendering: "pixelated", background: "#000" }} />
    </div>
  );
}

// ── Main App ─────────────────────────────────────────────────────────────────

type Renderer = "braille" | "halfblock";

function Demo() {
  const videoRef = useRef<HTMLVideoElement>(null);
  const imageRef = useRef<HTMLImageElement>(null);
  const [renderer, setRenderer] = useState<Renderer>("braille");
  const [sourceType, setSourceType] = useState<"video" | "image" | null>(null);
  const [source, setSource] = useState<string | null>(null);
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [cols, setCols] = useState(100);
  const [rows, setRows] = useState(45);
  const [imagePixels, setImagePixels] = useState<Uint8Array | null>(null);
  const [imageSize, setImageSize] = useState({ w: 0, h: 0 });
  const fileInputRef = useRef<HTMLInputElement>(null);
  const imageInputRef = useRef<HTMLInputElement>(null);

  const { pixels: videoPixels, size: videoSize, capture } = useVideoFrames(videoRef);
  const animRef = useRef<number>(0);

  const pixels = sourceType === "image" ? imagePixels : videoPixels;
  const size = sourceType === "image" ? imageSize : videoSize;

  // Render loop (video only)
  useEffect(() => {
    let running = true;
    function loop() {
      if (!running) return;
      capture();
      animRef.current = requestAnimationFrame(loop);
    }
    if (source && sourceType === "video") loop();
    return () => { running = false; cancelAnimationFrame(animRef.current); };
  }, [source, sourceType, capture]);

  // Cleanup stream on unmount
  useEffect(() => {
    return () => { stream?.getTracks().forEach((t) => t.stop()); };
  }, [stream]);

  const handleWebcam = useCallback(async () => {
    try {
      const s = await navigator.mediaDevices.getUserMedia({
        video: { width: { ideal: 1280 }, height: { ideal: 720 } },
      });
      stream?.getTracks().forEach((t) => t.stop());
      setStream(s);
      setImagePixels(null);
      setImageSize({ w: 0, h: 0 });
      if (videoRef.current) {
        videoRef.current.srcObject = s;
        videoRef.current.play();
      }
      setSourceType("video");
      setSource("webcam");
    } catch (e) {
      alert(`Webcam error: ${e}`);
    }
  }, [stream]);

  const handleVideoFile = useCallback(() => {
    fileInputRef.current?.click();
  }, []);

  const handleVideoFileChange = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    stream?.getTracks().forEach((t) => t.stop());
    setStream(null);
    setImagePixels(null);
    setImageSize({ w: 0, h: 0 });
    if (videoRef.current) {
      videoRef.current.srcObject = null;
      videoRef.current.src = URL.createObjectURL(file);
      videoRef.current.loop = true;
      videoRef.current.play();
    }
    setSourceType("video");
    setSource(file.name);
  }, [stream]);

  const handleImageFile = useCallback(() => {
    imageInputRef.current?.click();
  }, []);

  const handleImageFileChange = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    stream?.getTracks().forEach((t) => t.stop());
    setStream(null);
    if (videoRef.current) {
      videoRef.current.srcObject = null;
      videoRef.current.src = "";
    }
    cancelAnimationFrame(animRef.current);

    const img = imageRef.current;
    if (!img) return;
    const url = URL.createObjectURL(file);
    img.onload = () => {
      const w = img.naturalWidth;
      const h = img.naturalHeight;
      const canvas = document.createElement("canvas");
      canvas.width = w;
      canvas.height = h;
      const ctx = canvas.getContext("2d", { willReadFrequently: true })!;
      ctx.drawImage(img, 0, 0);
      const imageData = ctx.getImageData(0, 0, w, h);
      const rgb = new Uint8Array(w * h * 3);
      for (let i = 0, j = 0; i < imageData.data.length; i += 4, j += 3) {
        rgb[j] = imageData.data[i];
        rgb[j + 1] = imageData.data[i + 1];
        rgb[j + 2] = imageData.data[i + 2];
      }
      setImagePixels(rgb);
      setImageSize({ w, h });
      URL.revokeObjectURL(url);
    };
    img.src = url;
    setSourceType("image");
    setSource(file.name);
  }, [stream]);

  const handleDisconnect = useCallback(() => {
    stream?.getTracks().forEach((t) => t.stop());
    setStream(null);
    if (videoRef.current) {
      videoRef.current.srcObject = null;
      videoRef.current.src = "";
    }
    cancelAnimationFrame(animRef.current);
    setImagePixels(null);
    setImageSize({ w: 0, h: 0 });
    setSourceType(null);
    setSource(null);
  }, [stream]);

  const btnStyle = (active: boolean): React.CSSProperties => ({
    background: active ? "#0a2a0a" : "#1a1a1a",
    border: `1px solid ${active ? "#0f0" : "#333"}`,
    color: active ? "#0f0" : "#ccc",
    padding: "6px 14px",
    borderRadius: 4,
    cursor: "pointer",
    fontFamily: "inherit",
    fontSize: 12,
  });

  return (
    <div style={{ minHeight: "100vh", background: "#0a0a0a", color: "#e0e0e0", fontFamily: "'JetBrains Mono', monospace" }}>
      {/* Header */}
      <div style={{ padding: "16px 24px", borderBottom: "1px solid #222", display: "flex", alignItems: "center", gap: 12 }}>
        <h1 style={{ fontSize: 16, fontWeight: 600 }}>
          terminal-pixel-animation <span style={{ color: "#666" }}>::</span> React demo
        </h1>
        <span style={{ display: "inline-block", width: 8, height: 18, background: "#0f0", animation: "blink 1s step-end infinite" }} />
      </div>

      {/* Controls */}
      <div style={{ display: "flex", gap: 1, background: "#222" }}>
        <div style={{ background: "#0a0a0a", padding: "16px 24px", flex: 1 }}>
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 2, color: "#888", marginBottom: 12 }}>Renderer</div>
          <div style={{ display: "flex", gap: 8 }}>
            <button style={btnStyle(renderer === "braille")} onClick={() => setRenderer("braille")}>Braille (Odin)</button>
            <button style={btnStyle(renderer === "halfblock")} onClick={() => setRenderer("halfblock")}>Half-block (Zig)</button>
          </div>
        </div>
        <div style={{ background: "#0a0a0a", padding: "16px 24px", flex: 2 }}>
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 2, color: "#888", marginBottom: 12 }}>Source</div>
          <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
            <button style={btnStyle(false)} onClick={handleWebcam}>Webcam</button>
            <button style={btnStyle(false)} onClick={handleVideoFile}>Video file</button>
            <button style={btnStyle(false)} onClick={handleImageFile}>Image file</button>
            {source && (
              <button style={{ ...btnStyle(false), borderColor: "#a00", color: "#a00" }} onClick={handleDisconnect}>Disconnect</button>
            )}
            <label style={{ fontSize: 12, color: "#888" }}>
              Cols{" "}
              <input type="number" value={cols} min={10} max={300}
                onChange={(e) => setCols(Number(e.target.value))}
                style={{ background: "#111", border: "1px solid #333", color: "#ccc", padding: "4px 8px", width: 60, borderRadius: 3, fontFamily: "inherit", fontSize: 12, textAlign: "center" }}
              />
            </label>
            <label style={{ fontSize: 12, color: "#888" }}>
              Rows{" "}
              <input type="number" value={rows} min={5} max={150}
                onChange={(e) => setRows(Number(e.target.value))}
                style={{ background: "#111", border: "1px solid #333", color: "#ccc", padding: "4px 8px", width: 60, borderRadius: 3, fontFamily: "inherit", fontSize: 12, textAlign: "center" }}
              />
            </label>
            <div style={{ display: "flex", gap: 4 }}>
              {(["80x24", "100x45", "120x50", "160x60"] as const).map((preset) => {
                const [pCols, pRows] = preset.split("x").map(Number);
                const active = cols === pCols && rows === pRows;
                return (
                  <button key={preset} style={btnStyle(active)} onClick={() => { setCols(pCols); setRows(pRows); }}>
                    {preset}
                  </button>
                );
              })}
            </div>
          </div>
          <div style={{ fontSize: 11, color: "#666", marginTop: 8 }}>
            {source ? `Source: ${source}` : "Waiting for source..."}
          </div>
        </div>
      </div>

      {/* Canvas */}
      <div style={{ display: "flex", justifyContent: "center", padding: 24 }}>
        {pixels && size.w > 0 ? (
          renderer === "braille" ? (
            <BrailleCanvas pixels={pixels} width={size.w} height={size.h} cols={cols} rows={rows} />
          ) : (
            <HalfBlockCanvas pixels={pixels} width={size.w} height={size.h} cols={cols} rows={rows} />
          )
        ) : (
          <div style={{ color: "#444", fontSize: 14, padding: 48 }}>No source selected</div>
        )}
      </div>

      {/* Hidden elements */}
      <video ref={videoRef} autoPlay playsInline style={{ display: "none" }} />
      <img ref={imageRef} style={{ display: "none" }} crossOrigin="anonymous" />
      <input ref={fileInputRef} type="file" accept="video/*" onChange={handleVideoFileChange} style={{ display: "none" }} />
      <input ref={imageInputRef} type="file" accept="image/*" onChange={handleImageFileChange} style={{ display: "none" }} />

      <style>{`@keyframes blink { 50% { opacity: 0; } }`}</style>
    </div>
  );
}

export default function App() {
  return (
    <WasmProvider>
      <Demo />
    </WasmProvider>
  );
}