Skip to main content

ffai_core/
engine.rs

1//! One trait per task, many engines per trait.
2//!
3//! An *engine* is a named, swappable implementation of a task — exactly the
4//! role a codec plays in ffmpeg. Engines are registered in an
5//! [`crate::registry::EngineRegistry`] and selected by name.
6
7use std::fmt;
8use std::str::FromStr;
9
10use crate::error::Result;
11use crate::types::{
12    AudioBuffer, DetectOutput, ImageBuffer, OcrOutput, TimedSegment, Transcript, VideoFrame,
13};
14
15/// The tasks `FFai` knows about (the "stream types" of the toolkit).
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
17pub enum Task {
18    Asr,
19    Tts,
20    Ocr,
21    Vlm,
22    /// Object detection (Diana). The task exists ahead of its first engine so
23    /// `ffai bench detect` can baseline the world references (M-D0); the
24    /// `DetectEngine` trait and `DetectOutput` type land with the first
25    /// engine at M-D1.
26    Detect,
27    /// Monocular depth estimation (Diana). Shares Diana's backbone and neck
28    /// with [`Task::Detect`] — only the final head differs — but the output
29    /// is a dense metric map rather than boxes, so it is its own task.
30    Depth,
31}
32
33impl fmt::Display for Task {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        f.write_str(match self {
36            Self::Asr => "asr",
37            Self::Tts => "tts",
38            Self::Ocr => "ocr",
39            Self::Vlm => "vlm",
40            Self::Detect => "detect",
41            Self::Depth => "depth",
42        })
43    }
44}
45
46impl FromStr for Task {
47    type Err = String;
48
49    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
50        match s.to_ascii_lowercase().as_str() {
51            "asr" => Ok(Self::Asr),
52            "tts" => Ok(Self::Tts),
53            "ocr" => Ok(Self::Ocr),
54            "vlm" => Ok(Self::Vlm),
55            "detect" => Ok(Self::Detect),
56            other => Err(format!(
57                "unknown task `{other}` (expected asr, tts, ocr, vlm, or detect)"
58            )),
59        }
60    }
61}
62
63/// Honesty marker shown in `ffai engines` — stubs are visible, not hidden.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum EngineStatus {
66    /// Registered and selectable, returns `Error::NotImplemented`.
67    Stub,
68    /// Works, not yet oracle-gated against a reference implementation.
69    Experimental,
70    /// Oracle-gated against a reference implementation.
71    Stable,
72}
73
74impl fmt::Display for EngineStatus {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.write_str(match self {
77            Self::Stub => "stub",
78            Self::Experimental => "experimental",
79            Self::Stable => "stable",
80        })
81    }
82}
83
84/// Metadata every engine exposes for discovery (`ffai engines`).
85#[derive(Debug, Clone)]
86pub struct EngineInfo {
87    pub name: String,
88    pub task: Task,
89    pub status: EngineStatus,
90    pub description: String,
91}
92
93#[derive(Debug, Clone)]
94pub struct AsrOptions {
95    /// Force a language instead of auto-detecting.
96    pub language: Option<String>,
97    /// Word-level timestamps (WhisperX-style forced alignment).
98    pub word_timestamps: bool,
99    /// Speaker diarization (WhisperX-style).
100    pub diarize: bool,
101    /// Keep speaker identities across calls, so a voice heard in one chunk
102    /// keeps its label in the next.
103    ///
104    /// Off by default, and the default is the batch behaviour every
105    /// diarization system has: labels are arbitrary names for clusters within
106    /// ONE call, and `SPEAKER_00` in two separate calls need not be the same
107    /// person. That is fine for a file and useless for a stream.
108    ///
109    /// With this set, the engine keeps a speaker registry between calls. Call
110    /// `WhisperCandle::reset_speakers()` when a new recording begins — a new
111    /// session is a new set of people, and carrying identities across is
112    /// worse than starting fresh.
113    ///
114    /// Matching is deliberately stricter than in-call clustering: a registry
115    /// merge is permanent, and two people who share a centroid stay merged for
116    /// the rest of the session.
117    pub persist_speakers: bool,
118    /// Known speaker count, when the caller has one ("this is an interview,
119    /// two people"). Overrides the clustering threshold.
120    ///
121    /// Measured caution: with the threshold tuned this is **not** the safer
122    /// choice. Blind clustering scores 4.21 % DER against 5.00 % with the
123    /// true count supplied, because forcing a count forces a merge, and a bad
124    /// merge attributes one speaker's words to another. Set it when the count
125    /// is certain, not as insurance.
126    pub max_speakers: Option<usize>,
127    /// Cosine-distance threshold for merging speaker clusters.
128    ///
129    /// Swept against DER on a 6-conversation corpus: the minimum sits at
130    /// 0.85 (2.71 %), and 0.80 (4.21 %) ships instead because over-merging
131    /// fails catastrophically (44.7 % at 0.95) while over-splitting fails
132    /// gently. See `ffai_mercury::asr::diarize::DEFAULT_THRESHOLD`.
133    pub diarize_threshold: f32,
134    /// Translate to English instead of transcribing.
135    pub translate: bool,
136    /// Segment on speech before transcribing, so silence never reaches the
137    /// model.
138    ///
139    /// **On by default, for measured speed — not for quality.**
140    ///
141    /// - Audio with trailing silence: 2.2–4.2× faster, transcript byte-identical.
142    /// - Silent input: empty transcript, with no encoder pass at all.
143    /// - A live sliding window stops spending five encoder passes to produce
144    ///   nothing.
145    ///
146    /// Corpus WER *does* move with this on (test-clean 7.99 → 6.79,
147    /// test-other 16.79 → 16.43), and that is **not** a quality improvement —
148    /// do not cite it as one. Per-clip decomposition over 400 clips gives 38
149    /// improved and 38 worsened, a sign test of z = 0.00. VAD shifts where
150    /// speech sits inside Whisper's fixed 30 s context by ~0.2 s, which
151    /// re-rolls the decode on about a fifth of clips, half each way; the
152    /// aggregate moved because WER is dominated by a few high-delta clips.
153    /// Full descent: `docs/whys/vad-quality.md`.
154    ///
155    /// Set `false` for the unsegmented fixed-30 s-grid behaviour.
156    pub vad: bool,
157    /// Speech threshold, 0..1, higher being stricter. Only read when
158    /// [`Self::vad`] is set.
159    pub vad_threshold: f32,
160    /// Pack speech regions into windows of at most this many seconds.
161    pub vad_chunk_secs: f32,
162    /// Where this buffer starts in the wider stream, in seconds.
163    ///
164    /// Only meaningful for a streaming caller that re-sends a sliding window
165    /// (a live transcriber sending the trailing N seconds every tick). It
166    /// costs nothing to leave at `0.0`.
167    ///
168    /// **What it buys.** Diarization sub-segments each speech region into
169    /// 1.5 s windows and embeds each one — the dominant cost, ~172 ms apiece.
170    /// Those windows are placed relative to the region, and a region clipped
171    /// by the buffer's leading edge is anchored to the *buffer*, which moves.
172    /// So consecutive ticks re-cut the same audio at shifted offsets and every
173    /// embedding is recomputed. Measured on a 10 s window at a 1 s tick: the
174    /// window grids realign only every 3 s (`lcm(1.0, 0.75)`), and the cache
175    /// hit rate sat at ~24 %.
176    ///
177    /// Given this, windows are placed on an ABSOLUTE grid, so the same audio
178    /// yields the same window bounds no matter where the buffer happens to
179    /// start — which is what makes the embedding cache actually hit.
180    pub stream_offset_secs: f64,
181}
182
183impl Default for AsrOptions {
184    fn default() -> Self {
185        // Written out rather than derived: `vad_threshold` and
186        // `vad_chunk_secs` have meaningful defaults, and `#[derive(Default)]`
187        // would silently make them 0.0 — a threshold that calls everything
188        // speech and a window width that holds nothing.
189        Self {
190            language: None,
191            word_timestamps: false,
192            diarize: false,
193            persist_speakers: false,
194            max_speakers: None,
195            diarize_threshold: 0.80,
196            translate: false,
197            vad: true,
198            vad_threshold: 0.5,
199            vad_chunk_secs: 30.0,
200            stream_offset_secs: 0.0,
201        }
202    }
203}
204
205#[derive(Debug, Clone)]
206pub struct TtsOptions {
207    pub voice: Option<String>,
208    /// Playback-rate multiplier, 1.0 = normal.
209    pub speed: f32,
210    /// Acoustic variation (VITS prior noise); `None` = the voice's own
211    /// default. 0.0 is fully deterministic audio.
212    pub noise_scale: Option<f32>,
213    /// Duration variation (stochastic duration predictor noise); `None` =
214    /// voice default, 0.0 = deterministic timing.
215    pub noise_w: Option<f32>,
216    /// Seed for all sampled noise. Mercury synthesis is byte-stable per
217    /// (input, options, seed) — a capability the references do not offer.
218    pub seed: u64,
219    /// Silence inserted between sentences of long-form input, in seconds.
220    pub sentence_silence_s: f32,
221}
222
223impl Default for TtsOptions {
224    fn default() -> Self {
225        Self {
226            voice: None,
227            speed: 1.0,
228            noise_scale: None,
229            noise_w: None,
230            seed: 0,
231            sentence_silence_s: 0.2,
232        }
233    }
234}
235
236#[derive(Debug, Clone, Default)]
237pub struct OcrOptions {
238    /// Language hints (engine-specific tags); empty = engine default.
239    pub languages: Vec<String>,
240    /// The image IS one text line: skip detection, recognize the whole
241    /// frame as a single line (tesseract's `--psm 7`). LIVE's dirty-band
242    /// path sets this when a band's known geometry is a single line —
243    /// detection becomes async maintenance, recognition the only
244    /// synchronous work.
245    pub single_line: bool,
246    /// Restrict recognition to exactly these characters — `"0123456789$,.-"`
247    /// for an amount field, `"0123456789/"` for a date. `None` reads freely.
248    ///
249    /// For a field whose content class is known this removes a whole class of
250    /// look-alike errors (`1`→`T`, `0`→`O`, `5`→`S`) instead of leaving them
251    /// for the caller to guess at. The reported confidence is the model's own
252    /// probability for the character it was allowed to emit, NOT renormalised
253    /// over the allowed set, so a line the model wanted to read as letters
254    /// comes back with LOW confidence rather than as a confident digit.
255    ///
256    /// An engine that cannot constrain its decoder must return an error when
257    /// this is set — never read freely and ignore it. A character the model
258    /// cannot emit at all is also an error, naming the character.
259    pub charset: Option<String>,
260    /// Erase horizontal form rules (field lines, strike-throughs, table
261    /// rules) before reading. A typed value sitting on a field line fuses with
262    /// it — `1` reads as `T`, `0` as `U` — and the recognizer is confident
263    /// about the result. Off by default: it changes what every ruled page
264    /// reads, so it is asked for per call, by callers reading forms.
265    ///
266    /// Engines that do not implement it must return an error when it is set.
267    pub remove_rules: bool,
268    /// Detect which quarter turn makes the page upright, and read it that
269    /// way. Scanners store portrait forms sideways and phones photograph in
270    /// any orientation; read sideways, a page silently comes back as a few
271    /// low-confidence lines. Returned boxes stay in the INPUT image's
272    /// coordinates. Off by default: it costs an extra detection pass.
273    ///
274    /// Engines that do not implement it must return an error when it is set.
275    pub auto_orient: bool,
276}
277
278/// Detection options (Diana).
279///
280/// `confidence` defaults to 0.25 — the threshold a person looking at boxes
281/// wants. Benchmarks that need the low-confidence tail for mAP set it to
282/// ~0.001 explicitly, the way `corpora/refs/*_ref.py` do; the default is
283/// not tuned for the scorer, and the scorer does not inherit it silently.
284#[derive(Debug, Clone)]
285pub struct DetectOptions {
286    /// Minimum confidence to report.
287    pub confidence: f32,
288    /// Maximum detections returned, highest confidence first.
289    pub max_detections: usize,
290    /// Class-wise NMS `IoU`. `None` for the NMS-free one-to-one path, which
291    /// is YOLO26's default and needs no suppression.
292    pub iou: Option<f32>,
293    /// Restrict to these class ids; empty = every class.
294    pub classes: Vec<u32>,
295}
296
297impl Default for DetectOptions {
298    fn default() -> Self {
299        Self {
300            confidence: 0.25,
301            max_detections: 300,
302            iou: None,
303            classes: Vec::new(),
304        }
305    }
306}
307
308/// How a VLM decoder picks each next token.
309///
310/// **This is an enum rather than a bag of `Option` fields on purpose, and the
311/// reason is the whole of Gate 2's determinism requirement: there is no way to
312/// spell "sampling without a seed".** A `temperature: Option<f32>` beside a
313/// `seed: Option<u64>` lets a caller set one and forget the other, and the
314/// result is output that cannot be reproduced — silently, and only noticed
315/// when someone tries to re-run a ledger line.
316///
317/// Byte-stability is the one property every other `FFai` component already
318/// holds. `Mercury` TTS ships it as a competitive claim its reference
319/// structurally cannot match ([`TtsOptions::seed`]); Carmenta gates on
320/// byte-identity; `Diana` matches `PyTorch` detection-for-detection. `Argus` does
321/// not get to be the exception, so the type makes the exception
322/// unrepresentable.
323#[derive(Debug, Clone, PartialEq, Default)]
324pub enum Decoding {
325    /// Always the argmax. Deterministic by construction, and **the default**.
326    ///
327    /// `#[default]` rather than a hand-written `impl Default`: the default
328    /// belongs to the type, and a separate impl is one more place for it to
329    /// drift away from what this doc comment promises.
330    #[default]
331    Greedy,
332    /// Stochastic — and always seeded, because `seed` is not optional here.
333    ///
334    /// Same input + same options + same seed = same bytes.
335    Sampled {
336        /// Logit temperature. `1.0` is the model's own distribution.
337        temperature: f32,
338        /// Nucleus cutoff, `None` = disabled.
339        top_p: Option<f32>,
340        /// Top-k cutoff, `None` = disabled.
341        top_k: Option<usize>,
342        /// Not optional. See the type-level note above.
343        seed: u64,
344    },
345}
346
347/// One piece of a multimodal prompt.
348///
349/// Borrowed rather than owned: an `ImageBuffer` is the decoded raster, and a
350/// tiling VLM will re-encode it into a dozen-plus tiles anyway. Cloning it to
351/// build a prompt would copy megabytes for nothing.
352#[derive(Debug, Clone, PartialEq, Eq)]
353pub enum VlmPart<'a> {
354    Text(&'a str),
355    Image(&'a ImageBuffer),
356}
357
358/// An ordered, interleaved multimodal prompt — `text <img> text <img> text`.
359///
360/// **Order is the payload.** "Compare the first image to the second" is not
361/// expressible as a set of images plus a question, and a model that receives
362/// the images in the wrong order answers the wrong question fluently. So the
363/// prompt is a sequence and the engine splices its image-token blocks at the
364/// positions the sequence gives it.
365#[derive(Debug, Clone, Default, PartialEq, Eq)]
366pub struct VlmPrompt<'a> {
367    pub parts: Vec<VlmPart<'a>>,
368}
369
370impl<'a> VlmPrompt<'a> {
371    /// The single-image case: the image, then the instruction if there is one.
372    #[must_use]
373    pub fn single(image: &'a ImageBuffer, text: Option<&'a str>) -> Self {
374        let mut parts = vec![VlmPart::Image(image)];
375        if let Some(t) = text {
376            parts.push(VlmPart::Text(t));
377        }
378        Self { parts }
379    }
380
381    /// Number of images in the prompt — what an engine checks against the
382    /// image-token placeholders it is about to splice.
383    #[must_use]
384    pub fn image_count(&self) -> usize {
385        self.parts
386            .iter()
387            .filter(|p| matches!(p, VlmPart::Image(_)))
388            .count()
389    }
390}
391
392/// Options for a VLM call (Argus).
393///
394/// # Gate 2 — the v1 surface, and what is deliberately NOT here
395///
396/// Settled once, before implementation, because every field is cheap now and a
397/// breaking change later (`docs/plans/argus-launch-plan.md` §2 Gate 2).
398///
399/// **Excluded from v1, as decisions rather than oversights:**
400///
401/// - **Streaming.** Tokens as produced. It changes the return type of every
402///   method, so it is a trait redesign and not a field; it waits until there
403///   is a consumer that needs it.
404/// - **Grounding.** Region-in ("what is in this box") and grounded-out ("the
405///   dog `[x,y,w,h]`"). Diana already returns boxes; a second, weaker box
406///   source in the toolkit needs a reason beyond "the model can".
407/// - **Structured / JSON output.** Needs constrained decoding to be worth
408///   anything — an unconstrained "please reply in JSON" is a request, not a
409///   guarantee. High value for a tooling product, so it is v2 rather than
410///   never; mistral.rs already provides grammar-constrained decoding, which is
411///   what makes it cheap when it lands.
412/// - **Token-level confidence (logprobs).** Carmenta uses recognition
413///   confidence for its verifier and the analog is genuinely valuable, but it
414///   is only meaningful once an engine exists to produce it honestly.
415/// - **Conversation history / multi-turn.** [`VlmPrompt`] can already express
416///   an interleaved turn sequence; a typed history is a chat-session concern,
417///   and Argus is a media op.
418///
419/// **Not here because it belongs to the ENGINE, not the caller:** the chat
420/// template, the special vision tokens (`<image>`, `<|vision_start|>`), and
421/// the M-RoPE time axis for video. Those are properties of a specific
422/// checkpoint. Exposing them as options would invite a caller to set them
423/// wrong — and the launch plan measured what that costs: **43 of 50 answers
424/// changed** on identical weights purely from prompt formatting, with no error
425/// raised.
426#[derive(Debug, Clone, Default)]
427pub struct VlmOptions {
428    /// Instruction for the model; `None` = plain captioning.
429    ///
430    /// Read by [`VlmEngine::describe_image`] only. [`VlmEngine::describe`]
431    /// takes its text from the prompt's own [`VlmPart::Text`] parts, because
432    /// position matters there and a separate field could not say where the
433    /// text goes.
434    pub prompt: Option<String>,
435    /// Role/behaviour framing, when the checkpoint's template has a slot for
436    /// it. Engines without one must ignore it rather than concatenate it into
437    /// the user turn, which changes the prompt the model was tuned on.
438    pub system_prompt: Option<String>,
439    /// Token-selection strategy. Defaults to [`Decoding::Greedy`].
440    pub decoding: Decoding,
441    /// Token budget. `None` = the engine's own default.
442    pub max_new_tokens: Option<usize>,
443    /// Stop strings. Generation halts as soon as one is produced; the string
444    /// itself is not included in the returned text.
445    ///
446    /// EOS is not here — that is the tokenizer's, and an engine that needed to
447    /// be told its own EOS would be misconfigured.
448    pub stop: Vec<String>,
449    /// Frames shown to the model per video caption. `None` = the engine's own
450    /// default.
451    ///
452    /// This is the video knob that decides what a caption can be ABOUT, and
453    /// the arithmetic is worth stating because it is not obvious. A still
454    /// image is split into tiles so fine print survives — for `SmolVLM` that
455    /// is 17 tiles at 64 tokens, **1088 tokens per image**. A text tower with
456    /// 8192 positions therefore holds seven such frames, which is not a window
457    /// so much as a slideshow.
458    ///
459    /// Video engines turn splitting off, making a frame **one** tile, and the
460    /// same 8192 positions then hold a hundred. So this number trades fine
461    /// detail within a frame against temporal context across frames, and the
462    /// right value depends on the question being asked — which is why it is a
463    /// caller's option and not a constant.
464    ///
465    /// `1` degenerates to per-frame captioning: correct, and blind to motion.
466    pub frames_per_window: Option<usize>,
467    /// Repetition penalty, `None` = disabled.
468    ///
469    /// Sits beside [`Self::decoding`] rather than inside
470    /// [`Decoding::Sampled`] because it is a *logit* transform, not a
471    /// sampling one: it applies to greedy decoding too, and small models loop
472    /// under greedy more than under sampling.
473    pub repetition_penalty: Option<f32>,
474}
475
476/// Speech → text (Mercury).
477pub trait AsrEngine: Send + Sync {
478    fn info(&self) -> EngineInfo;
479    fn transcribe(&self, audio: &AudioBuffer, opts: &AsrOptions) -> Result<Transcript>;
480}
481
482/// Text → speech (Mercury).
483pub trait TtsEngine: Send + Sync {
484    fn info(&self) -> EngineInfo;
485    fn synthesize(&self, text: &str, opts: &TtsOptions) -> Result<AudioBuffer>;
486}
487
488/// Image → text (Carmenta).
489pub trait OcrEngine: Send + Sync {
490    fn info(&self) -> EngineInfo;
491    fn recognize(&self, image: &ImageBuffer, opts: &OcrOptions) -> Result<OcrOutput>;
492}
493
494/// Image → objects (Diana).
495/// What a depth engine returns: a dense map plus what is needed to place it
496/// back on the source image.
497#[derive(Debug, Clone)]
498pub struct DepthOutput {
499    /// Row-major depth, `height * width` values, in **metres**.
500    pub depth: Vec<f32>,
501    pub width: usize,
502    pub height: usize,
503    /// The letterbox that produced this map, when one was applied — the same
504    /// role it plays in [`DetectOutput`], and needed for the same reason: the
505    /// map is in letterboxed space and means nothing without it.
506    pub letterbox: Option<crate::types::Letterbox>,
507}
508
509impl DepthOutput {
510    /// Depth at a pixel of the map. `None` when out of range.
511    #[must_use]
512    pub fn at(&self, x: usize, y: usize) -> Option<f32> {
513        if x >= self.width || y >= self.height {
514            return None;
515        }
516        self.depth.get(y * self.width + x).copied()
517    }
518
519    /// `(min, max)` over the map, for callers normalising it for display.
520    /// Returns `None` for an empty map rather than a nonsense range.
521    #[must_use]
522    pub fn range(&self) -> Option<(f32, f32)> {
523        if self.depth.is_empty() {
524            return None;
525        }
526        let mut lo = f32::MAX;
527        let mut hi = f32::MIN;
528        for &v in &self.depth {
529            if v.is_finite() {
530                lo = lo.min(v);
531                hi = hi.max(v);
532            }
533        }
534        (lo <= hi).then_some((lo, hi))
535    }
536}
537
538/// Options for a depth run.
539#[derive(Debug, Clone, Default)]
540pub struct DepthOptions {
541    /// Resize the map to the SOURCE image's resolution and undo the
542    /// letterbox, instead of returning the raw network output at stride 4.
543    ///
544    /// Off by default: the raw map is what the model computed, and resizing
545    /// is a lossy convenience the caller may want to do differently.
546    pub full_resolution: bool,
547}
548
549/// Monocular depth estimation.
550pub trait DepthEngine: Send + Sync {
551    fn info(&self) -> EngineInfo;
552    fn depth(&self, image: &ImageBuffer, opts: &DepthOptions) -> Result<DepthOutput>;
553}
554
555pub trait DetectEngine: Send + Sync {
556    fn info(&self) -> EngineInfo;
557    fn detect(&self, image: &ImageBuffer, opts: &DetectOptions) -> Result<DetectOutput>;
558
559    /// Detect over many images, using the whole machine.
560    ///
561    /// **This is a first-class path, not a convenience wrapper**, because it
562    /// is where a detector's throughput actually lives. Measured on Diana:
563    /// running images concurrently is worth **3.6-5.3x** over calling
564    /// [`Self::detect`] in a loop, with byte-identical output and no change
565    /// whatever to the per-image path — because intra-image parallelism is
566    /// nearly exhausted (24 cores buy one image only 1.42x) while the images
567    /// themselves are independent.
568    ///
569    /// The trait is `Send + Sync`, so one loaded model serves every thread.
570    /// That is the structural advantage over the Python reference: measured
571    /// on the same machine, `PyTorch` gets *slower* under threading (0.68-0.72x)
572    /// because of the GIL, and its escape hatch — multiprocessing — pays a
573    /// full model copy per worker.
574    ///
575    /// The default implementation is sequential so existing engines keep
576    /// working; an engine that can do better should override it.
577    fn detect_batch(
578        &self,
579        images: &[ImageBuffer],
580        opts: &DetectOptions,
581    ) -> Result<Vec<DetectOutput>> {
582        images.iter().map(|i| self.detect(i, opts)).collect()
583    }
584    /// Class names for the ids in [`DetectOutput`], in id order. They come
585    /// from the weight manifest, so they belong to the engine rather than
586    /// to every output it produces.
587    fn class_names(&self) -> &[String];
588}
589
590/// Image/video → description (Argus).
591///
592/// See [`VlmOptions`] for the Gate-2 surface decision and the written-down v1
593/// exclusions.
594pub trait VlmEngine: Send + Sync {
595    fn info(&self) -> EngineInfo;
596
597    /// The general path: an ordered, interleaved multimodal prompt.
598    ///
599    /// **This is the required method, and `describe_image` is derived from
600    /// it, rather than the other way round.** An engine that implemented only
601    /// the single-image case would still compile against a multi-image
602    /// prompt — and would then silently answer using the first image, or the
603    /// last, or a concatenation. Making the general case the one an
604    /// implementor must write means multi-image support is a compile-time
605    /// obligation instead of a runtime surprise.
606    fn describe(&self, prompt: &VlmPrompt<'_>, opts: &VlmOptions) -> Result<String>;
607
608    /// One image, with [`VlmOptions::prompt`] as the instruction.
609    ///
610    /// Provided: builds a single-image [`VlmPrompt`] and calls
611    /// [`Self::describe`]. Zero-copy — the prompt borrows the image.
612    fn describe_image(&self, image: &ImageBuffer, opts: &VlmOptions) -> Result<String> {
613        self.describe(&VlmPrompt::single(image, opts.prompt.as_deref()), opts)
614    }
615
616    /// Video understanding over sampled frames → a timed caption track.
617    ///
618    /// Frames arrive with their timestamps ([`VideoFrame::timestamp`]) so an
619    /// engine can encode *time* and not merely order — M-RoPE's third axis.
620    /// Whether it does is the engine's business; the trait's job is to make
621    /// sure the information reaches it.
622    fn describe_video(
623        &self,
624        frames: &[VideoFrame],
625        opts: &VlmOptions,
626    ) -> Result<Vec<TimedSegment<String>>>;
627}
628
629#[cfg(test)]
630mod vlm_surface_tests {
631    use super::*;
632    use crate::types::PixelFormat;
633
634    fn img(byte: u8) -> ImageBuffer {
635        ImageBuffer {
636            width: 1,
637            height: 1,
638            format: PixelFormat::Rgb8,
639            data: vec![byte, byte, byte],
640        }
641    }
642
643    /// An engine that implements ONLY the required method and records what it
644    /// was handed — which is how we check `describe_image` really routes
645    /// through `describe` rather than being a second, divergent path.
646    struct Recorder(std::sync::Mutex<Vec<String>>);
647
648    impl VlmEngine for Recorder {
649        fn info(&self) -> EngineInfo {
650            EngineInfo {
651                name: "recorder".into(),
652                task: Task::Vlm,
653                status: EngineStatus::Stub,
654                description: String::new(),
655            }
656        }
657        fn describe(&self, prompt: &VlmPrompt<'_>, _opts: &VlmOptions) -> Result<String> {
658            let shape: Vec<String> = prompt
659                .parts
660                .iter()
661                .map(|p| match p {
662                    VlmPart::Text(t) => format!("text:{t}"),
663                    VlmPart::Image(i) => format!("image:{}", i.data[0]),
664                })
665                .collect();
666            self.0.lock().unwrap().push(shape.join("|"));
667            Ok(shape.join("|"))
668        }
669        fn describe_video(
670            &self,
671            _frames: &[VideoFrame],
672            _opts: &VlmOptions,
673        ) -> Result<Vec<TimedSegment<String>>> {
674            Ok(Vec::new())
675        }
676    }
677
678    /// Gate 2's determinism requirement, checked rather than asserted in prose:
679    /// a caller who sets nothing gets deterministic decoding.
680    #[test]
681    fn the_default_decoding_is_deterministic() {
682        assert_eq!(VlmOptions::default().decoding, Decoding::Greedy);
683        // ...and the default options carry no stochasticity anywhere else.
684        assert!(VlmOptions::default().stop.is_empty());
685        assert_eq!(VlmOptions::default().repetition_penalty, None);
686    }
687
688    /// There is no way to construct stochastic decoding without a seed. This
689    /// test cannot fail at runtime — the point is that the alternative does
690    /// not COMPILE, and this is where that intent is recorded.
691    #[test]
692    fn sampling_always_carries_a_seed() {
693        let d = Decoding::Sampled {
694            temperature: 0.7,
695            top_p: Some(0.9),
696            top_k: None,
697            seed: 42,
698        };
699        // Every Sampled value has a seed by construction; matching proves it.
700        let Decoding::Sampled { seed, .. } = d else {
701            panic!("expected Sampled")
702        };
703        assert_eq!(seed, 42);
704    }
705
706    #[test]
707    fn describe_image_routes_through_describe() {
708        let e = Recorder(std::sync::Mutex::new(Vec::new()));
709        let opts = VlmOptions {
710            prompt: Some("what is this?".into()),
711            ..VlmOptions::default()
712        };
713        let out = e.describe_image(&img(7), &opts).unwrap();
714        // Image FIRST, then the instruction — the order most VLM chat
715        // templates expect, and the order `VlmPrompt::single` documents.
716        assert_eq!(out, "image:7|text:what is this?");
717        assert_eq!(e.0.lock().unwrap().len(), 1, "describe must have been used");
718    }
719
720    #[test]
721    fn a_prompt_with_no_instruction_is_just_the_image() {
722        let e = Recorder(std::sync::Mutex::new(Vec::new()));
723        let out = e.describe_image(&img(3), &VlmOptions::default()).unwrap();
724        assert_eq!(out, "image:3");
725    }
726
727    /// Order is the payload: "compare the first to the second" is not
728    /// expressible as a set, so the sequence must survive intact.
729    #[test]
730    fn interleaved_order_is_preserved() {
731        let (a, b) = (img(1), img(2));
732        let e = Recorder(std::sync::Mutex::new(Vec::new()));
733        let prompt = VlmPrompt {
734            parts: vec![
735                VlmPart::Text("before"),
736                VlmPart::Image(&a),
737                VlmPart::Text("between"),
738                VlmPart::Image(&b),
739                VlmPart::Text("after"),
740            ],
741        };
742        assert_eq!(prompt.image_count(), 2);
743        let out = e.describe(&prompt, &VlmOptions::default()).unwrap();
744        assert_eq!(
745            out, "text:before|image:1|text:between|image:2|text:after",
746            "the sequence an engine receives must be the sequence it was given"
747        );
748    }
749}