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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Fluent configuration for `eger`'s image/video → ASCII pipelines.
//!
//! [`ConfigBuilder`] setters are infallible and chainable; every check (path
//! existence, regex compilation, `iascii` settings) happens centrally in
//! [`ConfigBuilder::build`], mirroring how `iascii::config::ConfigBuilder`
//! itself validates.

#[cfg(feature = "dither")]
use crate::dither::DitherOptions;
use crate::error::ConfigError;
#[cfg(feature = "script")]
use crate::script::Script;
use crate::style::Style;
use crate::system::SystemSpecs;
use iascii::config::{
    Config as AsciiConfig, ConfigBuilder as AsciiConfigBuilder, LuminanceMethod, OutputSizing,
};
use iascii::ramp::RampType;
use iascii::render::ColorDepth;
use regex::Regex;
use std::path::PathBuf;
use std::sync::{Arc, OnceLock};

/// Whether a [`Config`] describes an image or a video pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MediaType {
    Image,
    Video,
}

/// Where input files come from: a single file, or every file in a directory
/// whose name matches a regular expression.
#[derive(Debug, Clone)]
pub enum InputSource {
    File(PathBuf),
    Directory { dir: PathBuf, pattern: Regex },
}

/// A fully validated, immutable configuration produced by [`ConfigBuilder::build`].
///
/// Cheap to share across threads/tasks behind an `Arc<Config>` — build it
/// once and reuse it for every file in a batch or every frame of a video.
pub struct Config {
    pub media_type: MediaType,
    pub source: InputSource,
    pub output: Option<PathBuf>,
    pub num_threads: usize,
    pub color_depth: ColorDepth,
    pub ascii: AsciiConfig,
    /// How converted grids are painted (plain text, full color,
    /// black-and-white grayscale, single-color mono, 1-bit bilevel — see
    /// [`Style`]). Orthogonal to [`Config::color_depth`], which supplies
    /// the terminal depth for the styles that need one (`Full`, `Gray`,
    /// `Mono`). Defaults to [`Style::Full`].
    pub style: Style,
    /// Dithering applied when rendering, in place of `iascii`'s own plain
    /// per-cell nearest-palette color rounding — see [`crate::dither`].
    /// `None` (the default) means the usual undithered rendering.
    ///
    /// Requires the `dither` feature (on by default via `standard`).
    #[cfg(feature = "dither")]
    pub dither: Option<DitherOptions>,
    /// Cap on raw decoded bytes held per in-flight video chunk (see
    /// [`crate::system`]). Derived from detected RAM at build time unless
    /// overridden with [`ConfigBuilder::decode_chunk_bytes`]. Larger values
    /// raise throughput on big machines; smaller values lower peak RAM on
    /// small ones. The effective frame count per chunk is always at least
    /// one, no matter how small this is.
    pub decode_chunk_bytes: usize,
    /// Lazily-built Rayon pool shared by every call site that uses this
    /// `Config` (single-image, batch, and video frame conversion), so the
    /// pool is constructed at most once per `Config` instead of once per
    /// file/frame. See [`Config::thread_pool`].
    thread_pool: OnceLock<Arc<rayon::ThreadPool>>,
}

impl std::fmt::Debug for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut dbg = f.debug_struct("Config");
        dbg.field("media_type", &self.media_type)
            .field("source", &self.source)
            .field("output", &self.output)
            .field("num_threads", &self.num_threads)
            .field("color_depth", &self.color_depth)
            .field("ascii", &self.ascii)
            .field("style", &self.style)
            .field("decode_chunk_bytes", &self.decode_chunk_bytes);
        #[cfg(feature = "dither")]
        dbg.field("dither", &self.dither);
        dbg.field(
            "thread_pool",
            &self.thread_pool.get().map(|_| "<initialized>"),
        )
        .finish()
    }
}

impl Config {
    /// Starts building a new configuration for the given media type.
    pub fn builder(media_type: MediaType) -> ConfigBuilder {
        ConfigBuilder::new(media_type)
    }

    /// Returns the Rayon thread pool for this `Config`, building it on first
    /// use and reusing it for every subsequent call. Sized from
    /// [`Config::num_threads`] (0 means Rayon's own default).
    ///
    /// Call sites that used to build a fresh `ThreadPool` per file/frame
    /// (image batches, async single-image rendering, video streaming)
    /// should call this instead so the pool — and its worker OS threads —
    /// is created once per `Config` and shared.
    pub fn thread_pool(&self) -> Result<&Arc<rayon::ThreadPool>, ConfigError> {
        if self.thread_pool.get().is_none() {
            let mut builder = rayon::ThreadPoolBuilder::new();
            if self.num_threads > 0 {
                builder = builder.num_threads(self.num_threads);
            }
            let pool = builder
                .build()
                .map_err(|e| ConfigError::ThreadPool(e.to_string()))?;
            // If another thread raced us and already initialized the pool,
            // just discard the one we built; OnceLock::set is a no-op then.
            let _ = self.thread_pool.set(Arc::new(pool));
        }
        Ok(self
            .thread_pool
            .get()
            .expect("thread pool was just initialized above"))
    }

    /// Resolves [`InputSource`] into the concrete list of files to process,
    /// sorted for deterministic ordering across parallel batch runs.
    pub fn files(&self) -> Result<Vec<PathBuf>, ConfigError> {
        match &self.source {
            InputSource::File(path) => Ok(vec![path.clone()]),
            InputSource::Directory { dir, pattern } => {
                let mut matches: Vec<PathBuf> = std::fs::read_dir(dir)
                    .map_err(|source| ConfigError::Io {
                        path: dir.clone(),
                        source,
                    })?
                    .filter_map(|entry| entry.ok())
                    .map(|entry| entry.path())
                    .filter(|path| path.is_file())
                    .filter(|path| {
                        path.file_name()
                            .and_then(|name| name.to_str())
                            .is_some_and(|name| pattern.is_match(name))
                    })
                    .collect();

                if matches.is_empty() {
                    return Err(ConfigError::NoMatchingFiles {
                        dir: dir.clone(),
                        pattern: pattern.as_str().to_owned(),
                    });
                }

                matches.sort();
                Ok(matches)
            }
        }
    }
}

/// Builder for [`Config`].
///
/// `#[must_use]` on the type (rather than on each setter) catches the whole
/// class of "called `.output(...)` but forgot to reassign/chain it" bugs in
/// one place, since every setter returns `Self`.
#[must_use]
pub struct ConfigBuilder {
    media_type: MediaType,
    path: Option<PathBuf>,
    pattern: Option<String>,
    is_dir: bool,
    output: Option<PathBuf>,
    num_threads: Option<usize>,
    color_depth: ColorDepth,
    style: Style,
    decode_chunk_bytes: Option<usize>,
    ascii: AsciiConfigBuilder,
    #[cfg(feature = "dither")]
    dither: Option<DitherOptions>,
}

impl ConfigBuilder {
    pub fn new(media_type: MediaType) -> Self {
        Self {
            media_type,
            path: None,
            pattern: None,
            is_dir: false,
            output: None,
            num_threads: None,
            color_depth: ColorDepth::TrueColor,
            style: Style::Full,
            decode_chunk_bytes: None,
            ascii: AsciiConfigBuilder::new(),
            #[cfg(feature = "dither")]
            dither: None,
        }
    }

    /// Use a single file as input.
    pub fn from_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.path = Some(path.into());
        self.is_dir = false;
        self
    }

    /// Use every file in `dir` whose name matches `pattern` as input.
    pub fn from_dir(mut self, dir: impl Into<PathBuf>, pattern: impl Into<String>) -> Self {
        self.path = Some(dir.into());
        self.pattern = Some(pattern.into());
        self.is_dir = true;
        self
    }

    /// Sets the output file (single-file runs) or output directory
    /// (batch/video runs). Optional — leave unset when rendering straight to
    /// a `String`, `Vec<String>`, or stdout.
    pub fn output(mut self, path: impl Into<PathBuf>) -> Self {
        self.output = Some(path.into());
        self
    }

    /// Caps the number of worker threads used by Rayon for CPU-bound
    /// conversion work. Defaults to the machine's detected CPU count
    /// ([`crate::system::cpu_count`]); set it lower on shared boxes or
    /// higher only if you know the pool is undersized.
    pub fn num_threads(mut self, num_threads: usize) -> Self {
        self.num_threads = Some(num_threads);
        self
    }

    /// Caps raw decoded bytes buffered per in-flight video chunk (see
    /// [`crate::system`]). Defaults to ~1/32 of detected RAM (32 MiB –
    /// 512 MiB); set it explicitly to tune 4K throughput vs. peak memory
    /// yourself. The chunker always keeps at least one frame per chunk,
    /// so even `0` degrades gracefully instead of hanging.
    pub fn decode_chunk_bytes(mut self, bytes: usize) -> Self {
        self.decode_chunk_bytes = Some(bytes);
        self
    }

    /// Sets the terminal color capability used when rendering ANSI output.
    pub fn color_depth(mut self, depth: ColorDepth) -> Self {
        self.color_depth = depth;
        self
    }

    /// Picks how converted grids are painted — basic uncolored ASCII
    /// ([`Style::Plain`]), full color ([`Style::Full`], the default),
    /// black-and-white grayscale ([`Style::Gray`]), a single color of your
    /// choice ([`Style::Mono`]), or 1-bit bilevel ([`Style::BlackWhite`]).
    ///
    /// Depth still comes from [`ConfigBuilder::color_depth`] for the styles
    /// that use it. Dithering ([`ConfigBuilder::dither`]) applies to
    /// `Full` renders; the other styles ignore it.
    pub fn style(mut self, style: Style) -> Self {
        self.style = style;
        self
    }

    /// Caps output width, deriving height from the image/frame aspect ratio.
    pub fn max_width(mut self, max_width: usize) -> Self {
        self.ascii = self.ascii.output_sizing(OutputSizing::MaxWidth(max_width));
        self
    }

    /// Like [`ConfigBuilder::max_width`], but detects the cap from the
    /// current terminal's column count (via [`crate::render::terminal_size`])
    /// instead of taking a fixed number, so images/frames fit the terminal
    /// they're actually about to be printed to without the caller having to
    /// hardcode a width.
    ///
    /// Falls back to `fallback` when there's no attached terminal to query
    /// (output is piped/redirected, e.g. `eger-cli cat.png | less`) or its
    /// size can't be determined. Detection happens immediately when this is
    /// called, not lazily at [`ConfigBuilder::build`] — call it right
    /// before `build()` if the terminal might be resized in between.
    pub fn auto_width(mut self, fallback: usize) -> Self {
        let width = crate::render::terminal_size()
            .map(|(cols, _rows)| cols as usize)
            .unwrap_or(fallback);
        self.ascii = self.ascii.output_sizing(OutputSizing::MaxWidth(width));
        self
    }

    /// Fixes output width and height explicitly.
    pub fn explicit_dimensions(mut self, width: usize, height: usize) -> Self {
        self.ascii = self
            .ascii
            .output_sizing(OutputSizing::Explicit { width, height });
        self
    }

    /// Selects the character ramp used to map luminance to glyphs.
    pub fn ramp(mut self, ramp: RampType) -> Self {
        self.ascii = self.ascii.ramp(ramp);
        self
    }

    /// Selects the character ramp from a non-Latin [`Script`] instead of a
    /// raw [`RampType`] — shorthand for `.ramp(script.ramp_type(dark)?)`
    /// that silently falls back to the default ramp on the (practically
    /// unreachable, see [`Script::ramp`]'s docs) validation error, since
    /// every setter on this builder is otherwise infallible.
    ///
    /// Requires the `script` feature (on by default via `standard`).
    #[cfg(feature = "script")]
    pub fn script(mut self, script: Script, dark: bool) -> Self {
        if let Ok(ramp_type) = script.ramp_type(dark) {
            self.ascii = self.ascii.ramp(ramp_type);
        }
        self
    }

    /// Enables dithering (see [`crate::dither`]) for this configuration's
    /// renders. `None` (the default, if this is never called) renders
    /// with `iascii`'s usual undithered nearest-palette rounding.
    ///
    /// Requires the `dither` feature (on by default via `standard`).
    #[cfg(feature = "dither")]
    pub fn dither(mut self, options: DitherOptions) -> Self {
        self.dither = Some(options);
        self
    }

    /// Selects the luminance formula used to derive grayscale from RGB.
    pub fn luminance_method(mut self, method: LuminanceMethod) -> Self {
        self.ascii = self.ascii.luminance_method(method);
        self
    }

    /// Corrects for the non-square aspect ratio of terminal character cells.
    pub fn aspect_ratio_correction(mut self, factor: f32) -> Self {
        self.ascii = self.ascii.aspect_ratio_correction(factor);
        self
    }

    /// Minimum row count before `iascii` parallelizes conversion internally
    /// (requires `iascii`'s `parallel` feature).
    pub fn parallel_threshold(mut self, min_rows: usize) -> Self {
        self.ascii = self.ascii.parallel_threshold(min_rows);
        self
    }

    /// Validates all settings and produces an immutable [`Config`].
    pub fn build(self) -> Result<Config, ConfigError> {
        let path = self.path.ok_or(ConfigError::MissingSource)?;

        let source = if self.is_dir {
            if !path.is_dir() {
                return Err(ConfigError::FolderNotFound(path));
            }
            let pattern_str = self.pattern.unwrap_or_else(|| ".*".to_owned());
            let pattern = Regex::new(&pattern_str)
                .map_err(|source| ConfigError::InvalidRegexPattern(pattern_str, source))?;
            InputSource::Directory { dir: path, pattern }
        } else {
            if !path.is_file() {
                return Err(ConfigError::FileNotFound(path));
            }
            InputSource::File(path)
        };

        let ascii = self.ascii.build().map_err(ConfigError::Ascii)?;

        Ok(Config {
            media_type: self.media_type,
            source,
            output: self.output,
            num_threads: self.num_threads.unwrap_or_else(default_parallelism),
            color_depth: self.color_depth,
            ascii,
            style: self.style,
            decode_chunk_bytes: self.decode_chunk_bytes.unwrap_or_else(|| {
                crate::system::default_decode_chunk_bytes(SystemSpecs::detect())
            }),
            #[cfg(feature = "dither")]
            dither: self.dither,
            thread_pool: OnceLock::new(),
        })
    }
}

fn default_parallelism() -> usize {
    crate::system::cpu_count()
}

#[cfg(test)]
mod tests {
    use iascii::{ramp::SMOOTH_GRADIENT, Ramp};

    use super::*;
    use std::fs;

    fn tempdir() -> PathBuf {
        let mut dir = std::env::temp_dir();
        dir.push(format!(
            "eger-config-test-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn build_without_source_fails() {
        let err = Config::builder(MediaType::Image).build().unwrap_err();
        assert!(matches!(err, ConfigError::MissingSource));
    }

    #[test]
    fn build_with_missing_file_fails() {
        let err = Config::builder(MediaType::Image)
            .from_file("/definitely/does/not/exist.png")
            .build()
            .unwrap_err();
        assert!(matches!(err, ConfigError::FileNotFound(_)));
    }

    #[test]
    fn build_with_missing_dir_fails() {
        let err = Config::builder(MediaType::Video)
            .from_dir("/definitely/does/not/exist/dir", ".*")
            .build()
            .unwrap_err();
        assert!(matches!(err, ConfigError::FolderNotFound(_)));
    }

    #[test]
    fn build_with_invalid_regex_fails() {
        let dir = tempdir();
        let err = Config::builder(MediaType::Video)
            .from_dir(&dir, "[unterminated")
            .build()
            .unwrap_err();
        assert!(matches!(err, ConfigError::InvalidRegexPattern(_, _)));
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn build_from_file_succeeds_and_applies_defaults() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"not a real png, just needs to exist").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_file(&file)
            .build()
            .expect("build should succeed for an existing file");

        assert_eq!(config.media_type, MediaType::Image);
        assert!(matches!(config.source, InputSource::File(p) if p == file));
        assert_eq!(config.color_depth, ColorDepth::TrueColor);
        assert!(config.num_threads >= 1);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn explicit_settings_are_preserved() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();

        let config = Config::builder(MediaType::Video)
            .from_file(&file)
            .num_threads(3)
            .color_depth(ColorDepth::Ansi16)
            .max_width(80)
            .build()
            .unwrap();

        assert_eq!(config.num_threads, 3);
        assert_eq!(config.color_depth, ColorDepth::Ansi16);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn files_for_single_file_source_returns_that_file() {
        let dir = tempdir();
        let file = dir.join("a.png");
        fs::write(&file, b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_file(&file)
            .build()
            .unwrap();

        assert_eq!(config.files().unwrap(), vec![file]);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn files_for_directory_source_filters_sorts_and_dedupes_by_pattern() {
        let dir = tempdir();
        let a = dir.join("b_frame.png");
        let b = dir.join("a_frame.png");
        let skip = dir.join("frame.txt");
        fs::write(&a, b"stub").unwrap();
        fs::write(&b, b"stub").unwrap();
        fs::write(&skip, b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_dir(&dir, r"\.png$")
            .build()
            .unwrap();

        let files = config.files().unwrap();
        assert_eq!(files, vec![b.clone(), a.clone()], "results must be sorted");
        assert!(!files.contains(&skip));
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn files_for_directory_source_errors_when_nothing_matches() {
        let dir = tempdir();
        fs::write(dir.join("irrelevant.txt"), b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_dir(&dir, r"\.png$")
            .build()
            .unwrap();

        let err = config.files().unwrap_err();
        assert!(matches!(err, ConfigError::NoMatchingFiles { .. }));
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn from_dir_defaults_to_match_all_pattern() {
        let dir = tempdir();
        fs::write(dir.join("one"), b"stub").unwrap();
        fs::write(dir.join("two"), b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_dir(&dir, ".*")
            .build()
            .unwrap();

        assert_eq!(config.files().unwrap().len(), 2);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn output_setter_is_preserved_on_the_built_config() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();
        let out = dir.join("out.txt");

        let config = Config::builder(MediaType::Image)
            .from_file(&file)
            .output(&out)
            .build()
            .unwrap();

        assert_eq!(config.output, Some(out));
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn output_defaults_to_none_when_unset() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_file(&file)
            .build()
            .unwrap();

        assert_eq!(config.output, None);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn calling_from_file_after_from_dir_switches_to_a_single_file_source() {
        let dir = tempdir();
        let file = dir.join("only.png");
        fs::write(&file, b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_dir(&dir, r"\.png$")
            .from_file(&file)
            .build()
            .unwrap();

        assert!(matches!(config.source, InputSource::File(p) if p == file));
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn calling_from_dir_after_from_file_switches_to_a_directory_source() {
        let dir = tempdir();
        let file = dir.join("solo.png");
        fs::write(&file, b"stub").unwrap();
        fs::write(dir.join("other.png"), b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_file(&file)
            .from_dir(&dir, r"\.png$")
            .build()
            .unwrap();

        assert!(matches!(config.source, InputSource::Directory { .. }));
        assert_eq!(config.files().unwrap().len(), 2);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn num_threads_zero_is_preserved_as_given() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_file(&file)
            .num_threads(0)
            .build()
            .unwrap();

        assert_eq!(config.num_threads, 0);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn ramp_luminance_aspect_and_parallel_threshold_setters_all_chain_and_build() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();

        let result = Config::builder(MediaType::Image)
            .from_file(&file)
            .ramp(RampType::Dark(Ramp::SmoothGradient(SMOOTH_GRADIENT)))
            .luminance_method(LuminanceMethod::Bt601)
            .aspect_ratio_correction(2.0)
            .parallel_threshold(64)
            .build();

        assert!(
            result.is_ok(),
            "chaining ascii-forwarding setters should not break build(): {:?}",
            result.err()
        );
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn style_defaults_to_full_and_is_settable() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();

        let defaulted = Config::builder(MediaType::Image)
            .from_file(&file)
            .build()
            .unwrap();
        assert_eq!(defaulted.style, crate::style::Style::Full);

        let styled = Config::builder(MediaType::Image)
            .from_file(&file)
            .style(crate::style::Style::Mono(crate::rgb::Rgb::GREEN))
            .color_depth(ColorDepth::Ansi16)
            .build()
            .unwrap();
        assert_eq!(
            styled.style,
            crate::style::Style::Mono(crate::rgb::Rgb::GREEN)
        );
        // Depth stays orthogonal to style.
        assert_eq!(styled.color_depth, ColorDepth::Ansi16);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn decode_chunk_bytes_defaults_from_specs_and_is_overridable() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();

        let defaulted = Config::builder(MediaType::Image)
            .from_file(&file)
            .build()
            .unwrap();
        let expected =
            crate::system::default_decode_chunk_bytes(crate::system::SystemSpecs::detect());
        assert_eq!(defaulted.decode_chunk_bytes, expected);

        let manual = Config::builder(MediaType::Image)
            .from_file(&file)
            .decode_chunk_bytes(64 * 1024 * 1024)
            .build()
            .unwrap();
        assert_eq!(manual.decode_chunk_bytes, 64 * 1024 * 1024);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn explicit_dimensions_setter_does_not_error_on_build() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_file(&file)
            .explicit_dimensions(10, 5)
            .build()
            .unwrap();

        assert_eq!(config.media_type, MediaType::Image);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn media_type_is_preserved_through_build() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();

        let image_config = Config::builder(MediaType::Image)
            .from_file(&file)
            .build()
            .unwrap();
        let video_config = Config::builder(MediaType::Video)
            .from_file(&file)
            .build()
            .unwrap();

        assert_eq!(image_config.media_type, MediaType::Image);
        assert_eq!(video_config.media_type, MediaType::Video);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn directory_pattern_matching_is_case_sensitive() {
        let dir = tempdir();
        fs::write(dir.join("Frame.PNG"), b"stub").unwrap();
        fs::write(dir.join("frame.png"), b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_dir(&dir, r"\.png$")
            .build()
            .unwrap();

        let files = config.files().unwrap();
        assert_eq!(files, vec![dir.join("frame.png")]);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn thread_pool_is_built_lazily_and_reused_across_calls() {
        let dir = tempdir();
        let file = dir.join("input.png");
        fs::write(&file, b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_file(&file)
            .num_threads(2)
            .build()
            .unwrap();

        let first = config.thread_pool().unwrap();
        let second = config.thread_pool().unwrap();
        assert!(
            Arc::ptr_eq(first, second),
            "second call should reuse the pool built by the first"
        );
        assert_eq!(first.current_num_threads(), 2);
        fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn directory_source_ignores_subdirectories_even_if_name_matches() {
        let dir = tempdir();
        let nested = dir.join("frame.png");
        fs::create_dir_all(&nested).unwrap();
        let real_file = dir.join("real.png");
        fs::write(&real_file, b"stub").unwrap();

        let config = Config::builder(MediaType::Image)
            .from_dir(&dir, r"\.png$")
            .build()
            .unwrap();

        assert_eq!(config.files().unwrap(), vec![real_file]);
        fs::remove_dir_all(&dir).ok();
    }
}