eger 1.2.0

A high-level, parallel ASCII-art media pipeline built on top of iascii: images, video, GIFs, dithering, animated text/banners, and procedural illusions, all rendered to ANSI.
Documentation
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Image → ASCII rendering, with single-file, Rayon-parallel batch, and
//! Tokio-async entry points.
//!
//! Two independent kinds of Rayon parallelism are in play here, and it's
//! worth being explicit about which is which:
//! - **Across files/frames** ([`render_batch_parallel`],
//!   `video::stream_video_frames`): always on, doesn't need the
//!   `parallel` feature — this is plain `rayon::prelude::*` (`par_iter`)
//!   applied to a `Vec` of paths/frames this crate already owns.
//! - **Within one conversion** (`convert`, gated behind the `parallel`
//!   feature and forwarded to `iascii/parallel`'s `convert_with_pool`):
//!   splits a single image/frame's *rows* across the pool. Every
//!   conversion call site in this crate goes through `convert`, so
//!   whether a given call gets this row-level split is entirely
//!   `iascii::config::Config::parallel_threshold`'s call, not something
//!   decided here.
//!
//! Note: this module refers to the external `image` crate via a leading
//! `::image::...` path throughout, since the module itself is named `image`.

use crate::config::Config;
use crate::error::{EgerError, Result};
use crate::render::{self, RenderOutput, RenderTarget};
#[cfg(feature = "image")]
use ::image::AnimationDecoder;
use rayon::prelude::*;
use std::path::{Path, PathBuf};
#[cfg(feature = "video")]
use std::sync::Arc;
#[cfg(feature = "image")]
use std::time::Duration;

/// Converts one RGB8 buffer to an ASCII/ANSI [`iascii::grid::Grid`], the
/// shared entry point every image/frame conversion in this crate goes
/// through — so there is exactly one place that decides *how* a single
/// buffer gets converted, even though several call sites reuse it under
/// different outer contexts (a lone image, a batch item, a video/GIF
/// frame).
///
/// With the `parallel` feature (on by default — see `Cargo.toml`), this
/// routes through [`iascii::convert_with_pool`] using `config`'s cached
/// Rayon pool, giving row-level parallelism *within* one conversion.
/// iascii applies `config.ascii.parallel_threshold` internally, so a small
/// grid transparently still takes the sequential path — this never adds
/// pool overhead for a 40-row thumbnail, only for a genuinely large single
/// conversion.
///
/// Without `parallel`, this is exactly [`iascii::convert_image`] — no pool
/// is built or touched at all for pure sequential/single-image use, which
/// matters for e.g. `image_to_string` callers who never wanted a thread
/// pool in the first place.
///
/// Note on nested use: [`render_batch_parallel`] and
/// `video::stream_video_frames` already parallelize *across*
/// files/frames on this same cached pool before calling down into this
/// function. Calling `pool.install` again from inside a job already
/// running on that pool (as `convert_with_pool` does) is an explicitly
/// supported, non-deadlocking Rayon pattern — it just executes inline
/// rather than blocking on an idle pool — so nesting is safe, and
/// self-limiting in practice: most individual files/frames in a batch
/// don't clear `parallel_threshold` on their own, so the inner path only
/// actually engages for an outsized single item.
#[cfg(feature = "parallel")]
pub(crate) fn convert(
    width: u32,
    height: u32,
    buf: &[u8],
    config: &Config,
) -> Result<iascii::grid::Grid> {
    let pool = config.thread_pool()?;
    Ok(iascii::convert_with_pool(
        width,
        height,
        buf,
        &config.ascii,
        Some(pool.as_ref()),
    )?)
}

#[cfg(not(feature = "parallel"))]
pub(crate) fn convert(
    width: u32,
    height: u32,
    buf: &[u8],
    config: &Config,
) -> Result<iascii::grid::Grid> {
    Ok(iascii::convert_image(width, height, buf, &config.ascii)?)
}

/// Renders a single image file to `target` using `config`.
///
/// Requires the `image` feature (file decoding via the `image` crate).
#[cfg(feature = "image")]
pub fn render_image_file(
    path: &Path,
    config: &Config,
    target: &RenderTarget,
) -> Result<RenderOutput> {
    let img = ::image::open(path)?;
    render_dynamic_image(&img, config, target)
}

/// Renders an already-decoded image to `target` using `config`.
///
/// Requires the `image` feature (takes an `image`-crate `DynamicImage`).
///
/// The [`crate::style::Style`] on `config` picks the paint; when it is
/// [`crate::style::Style::Full`] *and* [`Config::dither`] is set, this
/// routes through [`crate::dither::render_ansi_dithered`] instead of
/// `iascii`'s own undithered per-cell rounding — see that module's docs
/// for why that matters most at
/// [`iascii::render::ColorDepth::Ansi16`]/`Ansi256`. Other styles render
/// directly and ignore `dither`.
///
/// For a dependency-free equivalent over raw pixels, see
/// [`render_rgb_buffer`].
#[cfg(feature = "image")]
pub fn render_dynamic_image(
    img: &::image::DynamicImage,
    config: &Config,
    target: &RenderTarget,
) -> Result<RenderOutput> {
    let rgb = img.to_rgb8();
    let width = rgb.width();
    let height = rgb.height();
    let grid = convert(width, height, rgb.as_raw(), config)?;
    render_grid_styled(&grid, config, target)
}

/// Renders one already-converted [`iascii::grid::Grid`] to `target`,
/// honoring [`Config::style`] (and [`Config::dither`] for
/// [`crate::style::Style::Full` when the `dither` feature is enabled).
pub(crate) fn render_grid_styled(
    grid: &iascii::grid::Grid,
    config: &Config,
    target: &RenderTarget,
) -> Result<RenderOutput> {
    // Dithering only ever applied to Full-style renders, mirroring the
    // historical behavior; every other style renders directly.
    #[cfg(feature = "dither")]
    if config.style == crate::style::Style::Full {
        if let Some(options) = &config.dither {
            let text = crate::dither::render_ansi_dithered(grid, config.color_depth, *options);
            return render::dispatch_text(target, text);
        }
    }
    match config.style {
        crate::style::Style::Full => render::dispatch(target, grid, Some(config.color_depth)),
        style => {
            let text = style.render(grid, config.color_depth);
            render::dispatch_text(target, text)
        }
    }
}

/// Renders a raw RGB8 framebuffer (`width * height * 3` bytes, row-major)
/// to `target` — no file, no `image`-crate decode.
///
/// This is the game-dev / realtime entry point: hand it a framebuffer
/// (screencap, software rasterizer, emulator output, ...) and get ASCII
/// back. Output sizing still comes from `config` (use
/// [`crate::config::ConfigBuilder::max_width`] or
/// [`explicit_dimensions`](crate::config::ConfigBuilder::explicit_dimensions)
/// to fit the ASCII grid to a HUD panel or terminal, not to the raw
/// framebuffer size), and memory stays flat — one grid plus one output
/// string, no whole-video buffering.
pub fn render_rgb_buffer(
    width: u32,
    height: u32,
    buf: &[u8],
    config: &Config,
    target: &RenderTarget,
) -> Result<RenderOutput> {
    let expected = width as usize * height as usize * 3;
    if buf.len() != expected {
        return Err(EgerError::Render(format!(
            "RGB8 buffer is {} bytes but {width}x{height} needs {expected}",
            buf.len()
        )));
    }
    let grid = convert(width, height, buf, config)?;
    render_grid_styled(&grid, config, target)
}

/// Async wrapper around [`render_image_file`]. Requires the `video`
/// feature (async runtime) and the `image` feature (file decoding).
#[cfg(all(feature = "video", feature = "image"))]
pub async fn render_image_file_async(
    path: PathBuf,
    config: Arc<Config>,
    target: RenderTarget,
) -> Result<RenderOutput> {
    let raw_bytes = tokio::fs::read(&path).await?;

    tokio::task::spawn_blocking(move || {
        let img = ::image::load_from_memory(&raw_bytes)?;
        let rgb = img.to_rgb8();
        let width = rgb.width();
        let height = rgb.height();
        let grid = convert(width, height, rgb.as_raw(), &config)?;

        render_grid_styled(&grid, &config, &target)
    })
    .await?
}

/// Renders every file resolved by `config.files()` in parallel on a
/// dedicated Rayon thread pool sized by `config.num_threads`.
///
/// Requires the `image` feature (file decoding via the `image` crate).
#[cfg(feature = "image")]
pub fn render_batch_parallel(
    config: &Config,
    target_for: impl Fn(&Path) -> RenderTarget + Sync,
) -> Result<Vec<(PathBuf, Result<RenderOutput>)>> {
    let files = config.files()?;
    let pool = config.thread_pool()?;

    let results = pool.install(|| {
        files
            .into_par_iter()
            .map(|path| {
                let target = target_for(&path);
                let outcome = render_image_file(&path, config, &target);
                (path, outcome)
            })
            .collect::<Vec<_>>()
    });

    Ok(results)
}

/// Async batch entrypoint. Requires the `video` feature (async runtime)
/// and the `image` feature (file decoding).
#[cfg(all(feature = "video", feature = "image"))]
pub async fn render_batch_async(
    config: Arc<Config>,
    target_for: impl Fn(&Path) -> RenderTarget + Send + Sync + 'static,
) -> Result<Vec<(PathBuf, Result<RenderOutput>)>> {
    let files = config.files()?;
    let target_for = Arc::new(target_for);
    let mut set = tokio::task::JoinSet::new();

    for path in files {
        let config = Arc::clone(&config);
        let target_for = Arc::clone(&target_for);
        set.spawn(async move {
            let target = target_for(&path);
            let outcome = render_image_file_async(path.clone(), config, target).await;
            (path, outcome)
        });
    }

    let mut results = Vec::with_capacity(set.len());
    while let Some(joined) = set.join_next().await {
        results.push(joined?);
    }
    Ok(results)
}

/// Convenience: render one image straight to an owned `String`.
/// Requires the `image` feature (file decoding via the `image` crate).
#[cfg(feature = "image")]
pub fn image_to_string(path: &Path, config: &Config) -> Result<String> {
    match render_image_file(path, config, &RenderTarget::String)? {
        RenderOutput::Text(text) => Ok(text),
        _ => unreachable!("RenderTarget::String always yields RenderOutput::Text"),
    }
}

/// Convenience: render one image straight to `Vec<String>`.
/// Requires the `image` feature (file decoding via the `image` crate).
#[cfg(feature = "image")]
pub fn image_to_lines(path: &Path, config: &Config) -> Result<Vec<String>> {
    match render_image_file(path, config, &RenderTarget::Lines)? {
        RenderOutput::Lines(lines) => Ok(lines),
        _ => unreachable!("RenderTarget::Lines always yields RenderOutput::Lines"),
    }
}

/// Convenience: render a raw RGB8 framebuffer straight to an owned
/// `String` (see [`render_rgb_buffer`]).
pub fn rgb_buffer_to_string(
    width: u32,
    height: u32,
    buf: &[u8],
    config: &Config,
) -> Result<String> {
    match render_rgb_buffer(width, height, buf, config, &RenderTarget::String)? {
        RenderOutput::Text(text) => Ok(text),
        _ => unreachable!("RenderTarget::String always yields RenderOutput::Text"),
    }
}

/// Decodes every frame of an animated GIF at `path` and renders each one to
/// ASCII lines, alongside that frame's display delay.
///
/// Reuses the same [`Config`]/`iascii` conversion pipeline as still images
/// (`render_dynamic_image`), so all the usual sizing/ramp/luminance/color
/// settings apply per-frame. This decodes and converts every frame eagerly
/// and holds them all in memory at once — fine for typical GIFs, but for a
/// very large one prefer streaming frame-by-frame the way
/// `video::stream_video_frames` does for video (not implemented
/// here, since `image`'s GIF decoder doesn't expose an easy async/streaming
/// frame source the way `ffmpeg`'s piped raw video does).
///
/// Requires the `image` feature (GIF decoding via the `image` crate).
#[cfg(feature = "image")]
pub fn gif_to_lines(path: &Path, config: &Config) -> Result<Vec<(Vec<String>, Duration)>> {
    let file = std::fs::File::open(path)?;
    let decoder = ::image::codecs::gif::GifDecoder::new(std::io::BufReader::new(file))
        .map_err(EgerError::Image)?;

    decoder
        .into_frames()
        .map(|frame| {
            let frame = frame.map_err(EgerError::Image)?;
            let (numer, denom) = frame.delay().numer_denom_ms();
            let delay = Duration::from_millis(numer as u64 / (denom.max(1)) as u64);

            let buffer = frame.into_buffer();
            let dynamic = ::image::DynamicImage::ImageRgba8(buffer);
            let lines = match render_dynamic_image(&dynamic, config, &RenderTarget::Lines)? {
                RenderOutput::Lines(lines) => lines,
                _ => unreachable!("RenderTarget::Lines always yields RenderOutput::Lines"),
            };
            Ok((lines, delay))
        })
        .collect()
}

/// Convenience: render one image straight to a file.
/// Requires the `image` feature (file decoding via the `image` crate).
#[cfg(feature = "image")]
pub fn image_to_file(path: &Path, config: &Config, output: Option<&Path>) -> Result<PathBuf> {
    let output = output
        .map(Path::to_path_buf)
        .or_else(|| config.output.clone())
        .ok_or_else(|| EgerError::Render("no output path provided or configured".into()))?;

    match render_image_file(path, config, &RenderTarget::File(output))? {
        RenderOutput::Written(path) => Ok(path),
        _ => unreachable!("RenderTarget::File always yields RenderOutput::Written"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::MediaType;
    #[cfg(feature = "image")]
    use ::image::codecs::gif::{GifEncoder, Repeat};
    #[cfg(feature = "image")]
    use ::image::{Delay, Frame, RgbaImage};

    #[cfg(feature = "image")]
    fn write_test_gif(path: &Path) {
        let mut file = std::fs::File::create(path).unwrap();
        let mut encoder = GifEncoder::new(&mut file);
        encoder.set_repeat(Repeat::Infinite).unwrap();

        // Two 2x2 frames: solid black, then solid white, each with a
        // distinct delay so we can assert both frame count and timing.
        let black = RgbaImage::from_pixel(2, 2, ::image::Rgba([0, 0, 0, 255]));
        let white = RgbaImage::from_pixel(2, 2, ::image::Rgba([255, 255, 255, 255]));
        encoder
            .encode_frame(Frame::from_parts(
                black,
                0,
                0,
                Delay::from_numer_denom_ms(50, 1),
            ))
            .unwrap();
        encoder
            .encode_frame(Frame::from_parts(
                white,
                0,
                0,
                Delay::from_numer_denom_ms(120, 1),
            ))
            .unwrap();
    }

    fn tempfile(name: &str) -> PathBuf {
        let mut path = std::env::temp_dir();
        path.push(format!("eger-image-test-{}-{name}", std::process::id()));
        path
    }

    #[test]
    fn convert_produces_a_grid_with_the_requested_dimensions() {
        let path = tempfile("convert-dummy.png");
        std::fs::write(&path, b"").unwrap();
        let config = Config::builder(MediaType::Image)
            .from_file(&path)
            .explicit_dimensions(3, 3)
            .build()
            .unwrap();

        // 3x3 solid-red RGB8 buffer.
        let buf = vec![255u8, 0, 0].repeat(9);
        let grid = convert(3, 3, &buf, &config).unwrap();
        assert_eq!(grid.width(), 3);
        assert_eq!(grid.height(), 3);
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn convert_handles_a_grid_large_enough_to_cross_the_parallel_threshold() {
        // iascii's default `parallel_threshold` is 100 rows; ask for well
        // past that so the `parallel`-feature path actually exercises
        // `convert_with_pool`'s pool-engaged branch rather than always
        // silently falling back to sequential.
        let path = tempfile("convert-large-dummy.png");
        std::fs::write(&path, b"").unwrap();
        let config = Config::builder(MediaType::Image)
            .from_file(&path)
            .explicit_dimensions(40, 150)
            .build()
            .unwrap();

        let buf = vec![128u8; 10 * 10 * 3]; // tiny 10x10 source, upsampled to 40x150
        let grid = convert(10, 10, &buf, &config).unwrap();
        assert_eq!(grid.height(), 150);
        std::fs::remove_file(&path).ok();
    }

    #[cfg(feature = "image")]
    #[test]
    fn render_batch_parallel_with_an_oversized_item_does_not_deadlock() {
        // Regression test for the nested-parallelism claim in `convert`'s
        // doc comment: render_batch_parallel already runs each file's
        // conversion inside `pool.install(|| files.into_par_iter()...)`;
        // this asserts that a batch item whose own grid is large enough to
        // additionally trigger `convert`'s inner `convert_with_pool` path
        // still completes (rather than hanging) when both levels share the
        // same underlying pool.
        let dir =
            std::env::temp_dir().join(format!("eger-nested-parallel-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        for name in ["a.png", "b.png"] {
            let img = ::image::RgbImage::from_pixel(4, 4, ::image::Rgb([200, 50, 50]));
            img.save(dir.join(name)).unwrap();
        }

        let config = Config::builder(MediaType::Image)
            .from_dir(&dir, r"\.png$")
            .explicit_dimensions(30, 120) // clears the default 100-row threshold
            .num_threads(2)
            .build()
            .unwrap();

        let results = render_batch_parallel(&config, |_| RenderTarget::Lines).unwrap();
        assert_eq!(results.len(), 2);
        for (_, outcome) in results {
            let output = outcome.unwrap();
            match output {
                RenderOutput::Lines(lines) => assert_eq!(lines.len(), 120),
                other => panic!("expected Lines, got {other:?}"),
            }
        }

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn render_rgb_buffer_rejects_a_wrong_sized_buffer() {
        let path = tempfile("buffer-dummy.png");
        std::fs::write(&path, b"").unwrap();
        let config = Config::builder(MediaType::Image)
            .from_file(&path)
            .explicit_dimensions(4, 4)
            .build()
            .unwrap();

        let bad = vec![0u8; 4 * 4 * 3 - 1];
        assert!(render_rgb_buffer(4, 4, &bad, &config, &RenderTarget::String).is_err());
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn render_rgb_buffer_honors_style_plain_and_mono() {
        let path = tempfile("buffer-styled-dummy.png");
        std::fs::write(&path, b"").unwrap();
        // Red-green gradient so mono shading visibly varies.
        let mut buf = Vec::with_capacity(8 * 4 * 3);
        for y in 0..4u32 {
            for x in 0..8u32 {
                buf.extend_from_slice(&[x as u8 * 32, y as u8 * 64, 40]);
            }
        }

        let plain_config = Config::builder(MediaType::Image)
            .from_file(&path)
            .explicit_dimensions(8, 4)
            .style(crate::style::Style::Plain)
            .build()
            .unwrap();
        let plain = rgb_buffer_to_string(8, 4, &buf, &plain_config).unwrap();
        assert!(!plain.contains('\x1b'));
        assert_eq!(plain.lines().count(), 4);

        let mono_config = Config::builder(MediaType::Image)
            .from_file(&path)
            .explicit_dimensions(8, 4)
            .style(crate::style::Style::Mono(crate::rgb::Rgb::GREEN))
            .build()
            .unwrap();
        let mono = rgb_buffer_to_string(8, 4, &buf, &mono_config).unwrap();
        assert!(mono.contains("38;2;"), "mono should emit color escapes");
        // Green tint: no red or blue channels anywhere.
        for line in mono.lines() {
            let mut rest = line;
            while let Some(start) = rest.find("38;2;") {
                let esc = &rest[start + 5..];
                let end = esc.find('m').unwrap();
                let parts: Vec<&str> = esc[..end].split(';').collect();
                assert_eq!(parts.len(), 3);
                assert_eq!(parts[0], "0");
                assert_eq!(parts[2], "0");
                rest = &esc[end..];
            }
        }
        std::fs::remove_file(&path).ok();
    }

    #[cfg(feature = "image")]
    #[test]
    fn gif_to_lines_decodes_every_frame_with_its_own_delay() {
        let path = tempfile("two-frame.gif");
        write_test_gif(&path);

        let config = Config::builder(MediaType::Image)
            .from_file(&path)
            .explicit_dimensions(2, 2)
            .build()
            .unwrap();

        let frames = gif_to_lines(&path, &config).unwrap();
        assert_eq!(frames.len(), 2, "should decode both encoded frames");
        assert_eq!(frames[0].1, Duration::from_millis(50));
        assert_eq!(frames[1].1, Duration::from_millis(120));
        for (lines, _) in &frames {
            assert_eq!(
                lines.len(),
                2,
                "explicit_dimensions height should be honored"
            );
        }

        std::fs::remove_file(&path).ok();
    }

    #[cfg(feature = "image")]
    #[test]
    fn gif_to_lines_errors_on_a_missing_file() {
        let config = Config::builder(MediaType::Image)
            .from_file(tempfile("does-not-exist.gif"))
            .build();
        // The file doesn't exist, so Config::build itself should already
        // reject it before we ever get to gif_to_lines.
        assert!(config.is_err());
    }
}