llama_cpp_4/mtmd.rs
1//! Safe wrappers for the `libmtmd` multimodal support library.
2//!
3//! `libmtmd` extends llama.cpp with the ability to encode image and audio
4//! inputs (bitmaps) into token embeddings that can then be fed into a
5//! standard [`crate::context::LlamaContext::decode`] call alongside normal text tokens.
6//!
7//! # Quick-start
8//!
9//! ```no_run
10//! # #[cfg(feature = "mtmd")]
11//! # {
12//! use std::path::Path;
13//! use llama_cpp_4::{
14//! llama_backend::LlamaBackend,
15//! model::{LlamaModel, params::LlamaModelParams, AddBos},
16//! context::params::LlamaContextParams,
17//! mtmd::{MtmdContext, MtmdContextParams, MtmdBitmap, MtmdInputChunks, MtmdInputText},
18//! };
19//!
20//! let backend = LlamaBackend::init().unwrap();
21//! let model = LlamaModel::load_from_file(&backend, Path::new("model.gguf"),
22//! &LlamaModelParams::default()).unwrap();
23//! let mut lctx = model.new_context(&backend, LlamaContextParams::default()).unwrap();
24//!
25//! // Load the multimodal projector (mmproj) model.
26//! let ctx_params = MtmdContextParams::default();
27//! let mut mtmd_ctx = MtmdContext::init_from_file(Path::new("mmproj.gguf"), &model, ctx_params)
28//! .unwrap();
29//!
30//! // Load an image from a file.
31//! let bitmap = MtmdBitmap::from_file(&mtmd_ctx, Path::new("image.jpg")).unwrap();
32//!
33//! // Tokenize a prompt that contains the media marker.
34//! let marker = MtmdContext::default_marker();
35//! let prompt = format!("Describe this image: {marker}");
36//! let text = MtmdInputText::new(&prompt, true, true);
37//! let bitmaps = [&bitmap];
38//!
39//! let mut chunks = MtmdInputChunks::new();
40//! mtmd_ctx.tokenize(&text, &bitmaps, &mut chunks).unwrap();
41//!
42//! // Evaluate / decode all chunks.
43//! let n_batch = lctx.n_batch() as i32;
44//! let mut n_past = 0i32;
45//! mtmd_ctx.eval_chunks(&mut lctx, &chunks, 0, 0, n_batch, true, &mut n_past).unwrap();
46//! # }
47//! ```
48//!
49//! # Feature flag
50//!
51//! This module is only compiled when the `mtmd` Cargo feature is enabled.
52
53use std::ffi::{CStr, CString};
54use std::os::raw::c_void;
55use std::path::Path;
56use std::ptr::NonNull;
57use std::slice;
58
59use llama_cpp_sys_4 as sys;
60
61use crate::model::LlamaModel;
62
63// ─────────────────────────────────────────────────────────────────────────────
64// Error types
65// ─────────────────────────────────────────────────────────────────────────────
66
67/// All errors that can be returned by the mtmd module.
68#[derive(Debug, thiserror::Error)]
69pub enum MtmdError {
70 /// The context could not be created (e.g. bad mmproj file).
71 #[error("failed to create mtmd context (null return from mtmd_init_from_file)")]
72 ContextCreateFailed,
73
74 /// The bitmap could not be created.
75 #[error("failed to create mtmd bitmap")]
76 BitmapCreateFailed,
77
78 /// A path could not be converted to a valid C string (embedded NUL byte or non-UTF-8).
79 #[error("invalid path: {0}")]
80 InvalidPath(#[from] std::ffi::NulError),
81
82 /// A path was not representable as UTF-8.
83 #[error("path is not valid UTF-8")]
84 PathNotUtf8,
85
86 /// `mtmd_tokenize` returned an error code.
87 #[error("tokenize error: code {0} (1 = bitmap count mismatch, 2 = preprocessing error)")]
88 TokenizeError(i32),
89
90 /// `mtmd_encode_chunk` returned a non-zero code.
91 #[error("encode error: code {0}")]
92 EncodeError(i32),
93
94 /// `mtmd_input_chunk_save` returned a non-zero code.
95 #[error("chunk save error: code {0}")]
96 ChunkSaveFailed(i32),
97
98 /// `mtmd_input_chunk_load` returned null — the buffer was not a chunk
99 /// this build can restore.
100 #[error("failed to load an input chunk from the buffer")]
101 ChunkLoadFailed,
102
103 /// A chunk could not be added to a batch.
104 #[error("batch add error: code {0} (2 = batch full, 3 = incompatible with existing chunks)")]
105 BatchAddFailed(i32),
106
107 /// `mtmd_batch_init` returned null.
108 #[error("failed to create an mtmd batch")]
109 BatchCreateFailed,
110
111 /// `mtmd_helper_eval_chunks` (or single-chunk variant) returned a non-zero code.
112 #[error("eval error: code {0}")]
113 EvalError(i32),
114
115 /// A video stream could not be opened. Common causes: the build lacks
116 /// video support (`MTMD_VIDEO` was OFF), `ffmpeg`/`ffprobe` is not on
117 /// `PATH`, or the file is unreadable.
118 #[error("failed to open video stream (null return from mtmd_helper_video_init)")]
119 VideoInitFailed,
120
121 /// `mtmd_helper_video_read_next` returned an error code (`-2`).
122 #[error("video read error: code {0}")]
123 VideoReadError(i32),
124
125 /// `mtmd_helper_resampler_init` returned null — it cannot handle that
126 /// rate pair.
127 #[error("failed to create resampler for {rate_in} Hz -> {rate_out} Hz")]
128 ResamplerInitFailed {
129 /// Requested input sample rate.
130 rate_in: i32,
131 /// Requested output sample rate.
132 rate_out: i32,
133 },
134
135 /// `mtmd_helper_resampler_process` reported a negative code.
136 #[error("resampler error: code {0}")]
137 ResampleError(i64),
138}
139
140/// A convenience `Result` alias for this module.
141pub type Result<T> = std::result::Result<T, MtmdError>;
142
143/// Progress callback invoked while the CLIP/mmproj weights are loading.
144///
145/// Receives a value in `[0.0, 1.0]`. Return `true` to continue loading or
146/// `false` to abort immediately.
147pub type MtmdProgressCallback = unsafe extern "C" fn(progress: f32, user_data: *mut c_void) -> bool;
148
149// ─────────────────────────────────────────────────────────────────────────────
150// MtmdContextParams
151// ─────────────────────────────────────────────────────────────────────────────
152
153/// Parameters used when creating an [`MtmdContext`].
154///
155/// Obtain a default-initialised instance via [`MtmdContextParams::default()`].
156pub struct MtmdContextParams {
157 pub(crate) params: sys::mtmd_context_params,
158}
159
160impl std::fmt::Debug for MtmdContextParams {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 f.debug_struct("MtmdContextParams")
163 .field("use_gpu", &self.params.use_gpu)
164 .field("print_timings", &self.params.print_timings)
165 .field("n_threads", &self.params.n_threads)
166 .field("warmup", &self.params.warmup)
167 .field("image_min_tokens", &self.params.image_min_tokens)
168 .field("image_max_tokens", &self.params.image_max_tokens)
169 .finish()
170 }
171}
172
173impl Default for MtmdContextParams {
174 fn default() -> Self {
175 // SAFETY: no pointer is involved; upstream returns a fully initialised struct by value.
176 let params = unsafe { sys::mtmd_context_params_default() };
177 Self { params }
178 }
179}
180
181impl MtmdContextParams {
182 /// Whether to run the vision/audio encoder on the GPU (default: `true`).
183 #[must_use]
184 pub fn use_gpu(mut self, v: bool) -> Self {
185 self.params.use_gpu = v;
186 self
187 }
188
189 /// Whether to print timing info after each encode (default: `false`).
190 #[must_use]
191 pub fn print_timings(mut self, v: bool) -> Self {
192 self.params.print_timings = v;
193 self
194 }
195
196 /// Number of threads used for the vision encoder (default taken from
197 /// `mtmd_context_params_default`).
198 #[must_use]
199 pub fn n_threads(mut self, n: i32) -> Self {
200 self.params.n_threads = n;
201 self
202 }
203
204 /// Whether to run a warm-up encode pass after initialisation.
205 #[must_use]
206 pub fn warmup(mut self, v: bool) -> Self {
207 self.params.warmup = v;
208 self
209 }
210
211 /// Minimum number of image tokens (0 = use model default).
212 #[must_use]
213 pub fn image_min_tokens(mut self, n: i32) -> Self {
214 self.params.image_min_tokens = n;
215 self
216 }
217
218 /// Maximum number of image tokens (0 = use model default).
219 #[must_use]
220 pub fn image_max_tokens(mut self, n: i32) -> Self {
221 self.params.image_max_tokens = n;
222 self
223 }
224
225 /// Maximum number of multimodal output tokens per batch.
226 ///
227 /// Maps to `mtmd_context_params.batch_max_tokens`. The upstream default
228 /// is `1024`. Increase for large images or long audio segments.
229 ///
230 /// # Examples
231 ///
232 /// ```rust
233 /// # #[cfg(feature = "mtmd")]
234 /// # {
235 /// use llama_cpp_4::mtmd::MtmdContextParams;
236 /// let params = MtmdContextParams::default().with_batch_max_tokens(2048);
237 /// assert_eq!(params.batch_max_tokens(), 2048);
238 /// # }
239 /// ```
240 #[must_use]
241 pub fn with_batch_max_tokens(mut self, n: i32) -> Self {
242 self.params.batch_max_tokens = n;
243 self
244 }
245
246 /// Get the configured batch token cap (`batch_max_tokens`).
247 #[must_use]
248 pub fn batch_max_tokens(&self) -> i32 {
249 self.params.batch_max_tokens
250 }
251
252 /// Set flash-attention mode for the vision encoder.
253 ///
254 /// Maps to `mtmd_context_params.flash_attn_type`. Uses the same
255 /// [`crate::context::params::LlamaFlashAttnType`] enum as text contexts.
256 ///
257 /// # Examples
258 ///
259 /// ```rust
260 /// # #[cfg(feature = "mtmd")]
261 /// # {
262 /// use llama_cpp_4::context::params::LlamaFlashAttnType;
263 /// use llama_cpp_4::mtmd::MtmdContextParams;
264 /// let params = MtmdContextParams::default()
265 /// .with_flash_attn_type(LlamaFlashAttnType::Auto);
266 /// assert_eq!(params.flash_attn_type(), LlamaFlashAttnType::Auto);
267 /// # }
268 /// ```
269 #[must_use]
270 pub fn with_flash_attn_type(
271 mut self,
272 flash_attn_type: crate::context::params::LlamaFlashAttnType,
273 ) -> Self {
274 self.params.flash_attn_type = flash_attn_type.into();
275 self
276 }
277
278 /// Get flash-attention mode for the vision encoder.
279 #[must_use]
280 pub fn flash_attn_type(&self) -> crate::context::params::LlamaFlashAttnType {
281 crate::context::params::LlamaFlashAttnType::from(self.params.flash_attn_type)
282 }
283
284 /// Register a callback invoked while mmproj weights load.
285 ///
286 /// Maps to `mtmd_context_params.progress_callback`. Pass `None` to disable
287 /// progress reporting. The callback may return `false` to abort loading
288 /// early; see [`MtmdProgressCallback`].
289 ///
290 /// `user_data` is forwarded to each invocation and must remain valid until
291 /// [`MtmdContext::init_from_file`] returns.
292 #[must_use]
293 pub fn with_progress_callback(
294 mut self,
295 callback: Option<MtmdProgressCallback>,
296 user_data: *mut c_void,
297 ) -> Self {
298 self.params.progress_callback = callback;
299 self.params.progress_callback_user_data = user_data;
300 self
301 }
302
303 /// Override the media marker string (e.g. `"<image>"`).
304 ///
305 /// The provided string must not contain interior NUL bytes. Pass `None`
306 /// to use the library default (`mtmd_default_marker()`).
307 ///
308 /// **Note:** the `CString` is stored inside the params so the pointer
309 /// remains valid as long as this `MtmdContextParams` lives.
310 /// # Errors
311 ///
312 /// Returns [`MtmdError`] if the marker string contains a NUL byte.
313 pub fn media_marker(mut self, marker: Option<&str>) -> std::result::Result<Self, MtmdError> {
314 match marker {
315 None => {
316 self.params.media_marker = std::ptr::null();
317 Ok(self)
318 }
319 Some(s) => {
320 let cs = CString::new(s)?;
321 self.params.media_marker = cs.as_ptr();
322 // Leak the CString so the raw pointer stays valid; the caller
323 // must ensure the params don't outlive the string. Since
324 // MtmdContextParams is consumed by MtmdContext::init_from_file,
325 // this is safe.
326 std::mem::forget(cs);
327 Ok(self)
328 }
329 }
330 }
331}
332
333// ─────────────────────────────────────────────────────────────────────────────
334// MtmdContext
335// ─────────────────────────────────────────────────────────────────────────────
336
337/// The main multimodal context.
338///
339/// Wraps a `mtmd_context *`. This context is tied to a specific mmproj model
340/// file and a loaded [`LlamaModel`]. It is safe to share across threads for
341/// `tokenize` calls (read-only), but `encode_chunk` / eval helpers mutate
342/// internal state and must not be called concurrently.
343pub struct MtmdContext {
344 ptr: NonNull<sys::mtmd_context>,
345 /// Elements in the buffer `mtmd_get_output_embd` points at, recorded by
346 /// the last successful [`encode_chunk`](MtmdContext::encode_chunk).
347 ///
348 /// upstream documents the size only in prose — `n_embd_inp(model) *
349 /// chunk.n_tokens()` — and offers no accessor for it, so the only way for
350 /// [`output_embd`](MtmdContext::output_embd) to be a safe function is to
351 /// remember it at the point it is known. `0` before any encode, which is
352 /// also what an empty slice means.
353 last_output_elements: usize,
354}
355
356// SAFETY: `Send` is sound because nothing in `mtmd_context` is tied to the
357// thread that created it.
358//
359// `Sync` is sound because every operation that mutates the context now takes
360// `&mut self` — `encode_chunk` and the three eval/decode helpers — so a shared
361// `&MtmdContext` can only reach the read-only accessors and `tokenize`, which
362// upstream synchronises internally. That was *not* true before: those methods
363// took `&self`, which let two threads encode through a shared reference while
364// a third held a slice from `output_embd`. The signatures are what makes this
365// claim hold, so moving any of them back to `&self` invalidates it.
366unsafe impl Send for MtmdContext {}
367// SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
368// remaining arguments are scalars or pointers valid for the call.
369unsafe impl Sync for MtmdContext {}
370
371impl std::fmt::Debug for MtmdContext {
372 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373 f.debug_struct("MtmdContext")
374 .field("ptr", &self.ptr)
375 .field("last_output_elements", &self.last_output_elements)
376 .finish()
377 }
378}
379
380impl Drop for MtmdContext {
381 fn drop(&mut self) {
382 // SAFETY: this runs once from `Drop`, the handle is non-null, and nothing
383 // reads it afterwards.
384 unsafe { sys::mtmd_free(self.ptr.as_ptr()) }
385 }
386}
387
388impl MtmdContext {
389 /// Returns the default media marker string used in prompts
390 /// (currently `"<__media__>"`).
391 #[must_use]
392 pub fn default_marker() -> &'static str {
393 // SAFETY: a read through a live handle (or no handle at all, for the
394 // library-wide accessors); the returned pointer is only converted
395 // below, never freed here.
396 let ptr = unsafe { sys::mtmd_default_marker() };
397 // SAFETY: the pointer comes from an mtmd accessor, which returns a static or
398 // handle-owned NUL-terminated string that outlives the borrow taken here.
399 unsafe { CStr::from_ptr(ptr) }
400 .to_str()
401 .unwrap_or("<__media__>")
402 }
403
404 /// Initialise a multimodal context from an mmproj GGUF file.
405 ///
406 /// # Parameters
407 ///
408 /// * `mmproj_path` – path to the mmproj `.gguf` file
409 /// * `text_model` – the already-loaded text model
410 /// * `params` – context parameters (use [`MtmdContextParams::default()`])
411 ///
412 /// # Errors
413 ///
414 /// Returns [`MtmdError::ContextCreateFailed`] if the underlying C call
415 /// returns a null pointer.
416 #[allow(clippy::needless_pass_by_value)]
417 pub fn init_from_file(
418 mmproj_path: impl AsRef<Path>,
419 text_model: &LlamaModel,
420 params: MtmdContextParams,
421 ) -> Result<Self> {
422 let path = mmproj_path
423 .as_ref()
424 .to_str()
425 .ok_or(MtmdError::PathNotUtf8)?;
426 let c_path = CString::new(path)?;
427
428 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
429 // and the model/context handles are borrowed — and the result is checked
430 // for null before being wrapped.
431 let ptr = unsafe {
432 sys::mtmd_init_from_file(c_path.as_ptr(), text_model.model.as_ptr(), params.params)
433 };
434
435 let ptr = NonNull::new(ptr).ok_or(MtmdError::ContextCreateFailed)?;
436 Ok(Self {
437 ptr,
438 last_output_elements: 0,
439 })
440 }
441
442 // ── Logging ──────────────────────────────────────────────────────────
443
444 /// Silence all clip/mtmd log output by installing a no-op callback.
445 ///
446 /// Call this right after [`init_from_file`](Self::init_from_file) to
447 /// suppress the verbose `clip_model_loader: tensor[N]…` lines that
448 /// clip.cpp emits to its own private logger (separate from `llama_log_set`).
449 pub fn void_logs() {
450 unsafe extern "C" fn noop(
451 _level: sys::ggml_log_level,
452 _text: *const ::std::os::raw::c_char,
453 _ud: *mut ::std::os::raw::c_void,
454 ) {
455 }
456 // SAFETY: the callback is a plain `extern "C"` function with no captured
457 // state, and the user-data pointer is null, which upstream allows.
458 unsafe { sys::mtmd_log_set(Some(noop), std::ptr::null_mut()) };
459 }
460
461 /// Like [`void_logs`](Self::void_logs), but additionally silences logs
462 /// emitted by the `mtmd_helper_*` layer (e.g. eval/decode helpers).
463 ///
464 /// Internally calls `mtmd_helper_log_set` which also routes through
465 /// `mtmd_log_set`, so this is a strict superset of `void_logs`.
466 pub fn void_helper_logs() {
467 unsafe extern "C" fn noop(
468 _level: sys::ggml_log_level,
469 _text: *const ::std::os::raw::c_char,
470 _ud: *mut ::std::os::raw::c_void,
471 ) {
472 }
473 // SAFETY: the callback is a plain `extern "C"` function with no captured
474 // state, and the user-data pointer is null, which upstream allows.
475 unsafe { sys::mtmd_helper_log_set(Some(noop), std::ptr::null_mut()) };
476 }
477
478 // ── Capability queries ────────────────────────────────────────────────
479
480 /// Returns `true` if the model supports vision (image) input.
481 #[must_use]
482 pub fn supports_vision(&self) -> bool {
483 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
484 // remaining arguments are scalars or pointers valid for the call.
485 unsafe { sys::mtmd_support_vision(self.ptr.as_ptr()) }
486 }
487
488 /// Returns `true` if the model supports audio input.
489 #[must_use]
490 pub fn supports_audio(&self) -> bool {
491 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
492 // remaining arguments are scalars or pointers valid for the call.
493 unsafe { sys::mtmd_support_audio(self.ptr.as_ptr()) }
494 }
495
496 /// Returns `true` if this build and model support video input.
497 ///
498 /// Video support additionally requires `ffmpeg`/`ffprobe` to be available
499 /// at runtime (see [`MtmdVideo`]). Wraps `mtmd_helper_support_video`.
500 #[must_use]
501 #[deprecated(
502 since = "0.10.0",
503 note = "upstream deprecated `mtmd_helper_support_video`; use `capabilities(model).video`"
504 )]
505 pub fn supports_video(&self) -> bool {
506 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
507 // remaining arguments are scalars or pointers valid for the call.
508 unsafe { sys::mtmd_helper_support_video(self.ptr.as_ptr()) }
509 }
510
511 /// Everything this model and projector can take in and produce.
512 ///
513 /// Replaces the two single-purpose predicates upstream deprecated in
514 /// `b12032` ([`supports_video`](Self::supports_video) and
515 /// [`model_can_chat`](Self::model_can_chat)), and reports six more
516 /// capabilities besides — notably whether the model can *generate* audio,
517 /// and whether it accepts a speaker reference for voice cloning.
518 ///
519 /// Wraps `mtmd_helper_get_capabilities`. Note it is keyed on the **model**,
520 /// not a context, because that is what the capabilities are a property of.
521 #[must_use]
522 pub fn capabilities(&self, model: &crate::model::LlamaModel) -> MtmdCapabilities {
523 // SAFETY: both pointers are borrowed from live values for the duration
524 // of the call, and upstream documents a null `mctx` as valid (meaning a
525 // text-only model) — ours is never null, which is the stronger case.
526 let raw =
527 unsafe { sys::mtmd_helper_get_capabilities(model.model.as_ptr(), self.ptr.as_ptr()) };
528 MtmdCapabilities {
529 chat: raw.chat,
530 vision: raw.vision,
531 audio: raw.audio,
532 video: raw.video,
533 audio_stream: raw.audio_stream,
534 text_gen: raw.text_gen,
535 audio_gen: raw.audio_gen,
536 audio_gen_spk_ref: raw.audio_gen_spk_ref,
537 }
538 }
539
540 /// Returns the media marker string configured for *this* context.
541 ///
542 /// Unlike [`default_marker`](Self::default_marker) (the library-wide
543 /// default), this reflects any override passed via
544 /// [`MtmdContextParams::media_marker`]. Wraps `mtmd_get_marker`.
545 #[must_use]
546 pub fn marker(&self) -> &str {
547 // SAFETY: a read through a live handle (or no handle at all, for the
548 // library-wide accessors); the returned pointer is only converted
549 // below, never freed here.
550 let ptr = unsafe { sys::mtmd_get_marker(self.ptr.as_ptr()) };
551 if ptr.is_null() {
552 return Self::default_marker();
553 }
554 // SAFETY: the pointer comes from an mtmd accessor, which returns a static or
555 // handle-owned NUL-terminated string that outlives the borrow taken here.
556 unsafe { CStr::from_ptr(ptr) }
557 .to_str()
558 .unwrap_or_else(|_| Self::default_marker())
559 }
560
561 /// Returns the audio sample rate in Hz (e.g. `16_000` for Whisper), or `-1` if
562 /// audio is not supported.
563 #[must_use]
564 pub fn audio_sample_rate(&self) -> i32 {
565 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
566 // remaining arguments are scalars or pointers valid for the call.
567 unsafe { sys::mtmd_get_audio_sample_rate(self.ptr.as_ptr()) }
568 }
569
570 /// Whether `llama_decode` must use a non-causal attention mask when
571 /// decoding image embeddings for this model.
572 #[must_use]
573 pub fn decode_use_non_causal(&self, chunk: &MtmdInputChunk<'_>) -> bool {
574 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
575 // remaining arguments are scalars or pointers valid for the call.
576 unsafe { sys::mtmd_decode_use_non_causal(self.ptr.as_ptr(), chunk.as_ptr()) }
577 }
578
579 /// Whether the model uses M-RoPE for `llama_decode`.
580 #[must_use]
581 pub fn decode_use_mrope(&self) -> bool {
582 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
583 // remaining arguments are scalars or pointers valid for the call.
584 unsafe { sys::mtmd_decode_use_mrope(self.ptr.as_ptr()) }
585 }
586
587 // ── Core API ──────────────────────────────────────────────────────────
588
589 /// Tokenize a text prompt that contains one or more media markers.
590 ///
591 /// The number of `bitmaps` must equal the number of media markers in the
592 /// prompt text, otherwise [`MtmdError::TokenizeError`] with code `1` is returned.
593 ///
594 /// This call is **thread-safe** (shared `&self`).
595 ///
596 /// # Parameters
597 ///
598 /// * `text` – text + tokenisation options
599 /// * `bitmaps` – slice of [`MtmdBitmap`] references, one per media marker
600 /// * `output` – an [`MtmdInputChunks`] that will be populated with the result
601 ///
602 /// # Errors
603 ///
604 /// Returns [`MtmdError::TokenizeError`] if tokenization fails.
605 pub fn tokenize(
606 &self,
607 text: &MtmdInputText<'_>,
608 bitmaps: &[&MtmdBitmap],
609 output: &mut MtmdInputChunks,
610 ) -> Result<()> {
611 // The C signature is: mtmd_tokenize(..., mtmd_bitmap ** bitmaps, ...)
612 // where each element is a `const mtmd_bitmap *`. We build a Vec of
613 // `*const mtmd_bitmap` and pass a mutable pointer to its first element
614 // (i.e. `*mut *const mtmd_bitmap`) to satisfy the C API.
615 let mut bitmap_ptrs: Vec<*const sys::mtmd_bitmap> = bitmaps
616 .iter()
617 .map(|b| b.ptr.as_ptr().cast_const())
618 .collect();
619
620 // Length-delimited (llama.cpp #25548), so interior NULs are preserved.
621 let c_text = text.as_raw();
622
623 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
624 // remaining arguments are scalars or pointers valid for the call.
625 let ret = unsafe {
626 sys::mtmd_tokenize(
627 self.ptr.as_ptr(),
628 output.ptr.as_ptr(),
629 &raw const c_text,
630 bitmap_ptrs.as_mut_ptr(),
631 bitmap_ptrs.len(),
632 )
633 };
634
635 if ret != 0 {
636 return Err(MtmdError::TokenizeError(ret));
637 }
638 Ok(())
639 }
640
641 /// Tokenize an explicit sequence of parts, without media markers.
642 ///
643 /// [`Self::tokenize`] splices bitmaps in wherever the prompt contains the
644 /// media marker, which means the marker string has to be embedded in the
645 /// text and cannot itself be user content. This takes the interleaving
646 /// directly, so:
647 ///
648 /// - a marker appearing in user text is just text, not a splice point;
649 /// - `parse_special` is per text part, so a system prompt can enable
650 /// special tokens while user content does not.
651 ///
652 /// `add_special` applies once to the whole sequence — upstream ignores the
653 /// per-part flag.
654 ///
655 /// Wraps `mtmd_tokenize_from_parts`.
656 ///
657 /// # Errors
658 ///
659 /// Returns [`MtmdError::TokenizeError`] — code `1` means a part carried
660 /// both text and a bitmap, or neither.
661 pub fn tokenize_from_parts(
662 &self,
663 parts: &[MtmdInputPart<'_>],
664 add_special: bool,
665 output: &mut MtmdInputChunks,
666 ) -> Result<()> {
667 // Three levels have to stay alive across the call: the C text structs,
668 // the parts that point at them, and the array of pointers to those
669 // parts. Building them in that order keeps every borrow valid.
670 let raw_texts: Vec<sys::mtmd_input_text> = parts
671 .iter()
672 .filter_map(|part| match part {
673 MtmdInputPart::Text(text) => Some(text.as_raw()),
674 MtmdInputPart::Bitmap(_) => None,
675 })
676 .collect();
677
678 let mut next_text = 0usize;
679 let raw_parts: Vec<sys::mtmd_input_part> = parts
680 .iter()
681 .map(|part| match part {
682 MtmdInputPart::Text(_) => {
683 let raw = &raw_texts[next_text];
684 next_text += 1;
685 sys::mtmd_input_part {
686 text: std::ptr::from_ref(raw),
687 bitmap: std::ptr::null(),
688 }
689 }
690 MtmdInputPart::Bitmap(bitmap) => sys::mtmd_input_part {
691 text: std::ptr::null(),
692 bitmap: bitmap.ptr.as_ptr().cast_const(),
693 },
694 })
695 .collect();
696 let part_ptrs: Vec<*const sys::mtmd_input_part> =
697 raw_parts.iter().map(std::ptr::from_ref).collect();
698
699 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
700 // remaining arguments are scalars or pointers valid for the call.
701 let ret = unsafe {
702 sys::mtmd_tokenize_from_parts(
703 self.ptr.as_ptr(),
704 output.ptr.as_ptr(),
705 part_ptrs.as_ptr(),
706 part_ptrs.len(),
707 add_special,
708 )
709 };
710 if ret != 0 {
711 return Err(MtmdError::TokenizeError(ret));
712 }
713 Ok(())
714 }
715
716 /// Audio-generation capabilities of the loaded mmproj.
717 ///
718 /// Returns `None` when this projector cannot generate audio, which is the
719 /// case for every vision-only mmproj.
720 ///
721 /// Wraps `mtmd_gen_audio_get_info`.
722 #[must_use]
723 pub fn gen_audio_info(&self) -> Option<MtmdGenAudioInfo> {
724 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
725 // remaining arguments are scalars or pointers valid for the call.
726 let info = unsafe { sys::mtmd_gen_audio_get_info(self.ptr.as_ptr()) };
727 if info.type_ == sys::MTMD_GEN_AUDIO_TYPE_NONE {
728 return None;
729 }
730 let variant = if info.model_variant.is_null() {
731 None
732 } else {
733 Some(
734 // SAFETY: the pointer comes from an mtmd accessor, which returns a static or
735 // handle-owned NUL-terminated string that outlives the borrow taken here.
736 unsafe { CStr::from_ptr(info.model_variant) }
737 .to_string_lossy()
738 .into_owned(),
739 )
740 };
741 Some(MtmdGenAudioInfo {
742 pipeline: MtmdGenAudioType::from_raw(info.type_),
743 sample_rate: info.sample_rate,
744 model_variant: variant,
745 })
746 }
747
748 /// Whether this model and projector can be used for chat.
749 ///
750 /// Wraps `mtmd_helper_model_can_chat`.
751 #[must_use]
752 #[deprecated(
753 since = "0.10.0",
754 note = "upstream deprecated `mtmd_helper_model_can_chat`; use `capabilities(model).chat`"
755 )]
756 pub fn model_can_chat(&self, ctx: &crate::context::LlamaContext<'_>) -> bool {
757 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
758 // remaining arguments are scalars or pointers valid for the call.
759 unsafe { sys::mtmd_helper_model_can_chat(ctx.context.as_ptr(), self.ptr.as_ptr()) }
760 }
761
762 /// Encode a single input chunk (image or audio) and store the resulting
763 /// embeddings inside the context.
764 ///
765 /// After a successful call, the embeddings can be retrieved with
766 /// [`MtmdContext::output_embd`].
767 ///
768 /// This call is **NOT thread-safe**.
769 ///
770 /// # Errors
771 ///
772 /// Returns [`MtmdError::EncodeError`] if encoding fails.
773 pub fn encode_chunk(&mut self, model: &LlamaModel, chunk: &MtmdInputChunk<'_>) -> Result<()> {
774 // SAFETY: a live `&mut self` gives an exclusive, non-null context, and
775 // `chunk` is owned by the caller and valid for the call.
776 let ret = unsafe { sys::mtmd_encode_chunk(self.ptr.as_ptr(), chunk.ptr) };
777 if ret != 0 {
778 return Err(MtmdError::EncodeError(ret));
779 }
780 // Record what the output buffer now holds, while it is knowable.
781 // Saturating rather than wrapping: a product this large cannot be a
782 // real buffer, and a wrapped value would be a short slice over a long
783 // one, which is the dangerous direction.
784 self.last_output_elements = usize::try_from(model.n_embd_inp())
785 .unwrap_or(0)
786 .saturating_mul(chunk.n_tokens());
787 Ok(())
788 }
789
790 /// Return a slice over the embeddings produced by the last
791 /// [`encode_chunk`](Self::encode_chunk) call.
792 ///
793 /// The length (in `f32` elements) is:
794 /// ```text
795 /// n_embd_inp(model) * chunk.n_tokens()
796 /// ```
797 ///
798 /// # Safety
799 ///
800 /// The returned slice is valid until the next call that mutates the
801 /// context (e.g. another `encode_chunk`).
802 #[must_use]
803 pub fn output_embd(&self) -> &[f32] {
804 if self.last_output_elements == 0 {
805 return &[];
806 }
807 // SAFETY: the pointer belongs to this context and is non-null once an
808 // encode has run — which `last_output_elements != 0` implies, since it
809 // is only set by a successful `encode_chunk`. That same call recorded
810 // the element count from the chunk it encoded, so the slice stays
811 // inside the buffer. The borrow is tied to `&self` and `encode_chunk`
812 // takes `&mut self`, so the slice cannot outlive the data.
813 unsafe {
814 let ptr = sys::mtmd_get_output_embd(self.ptr.as_ptr());
815 if ptr.is_null() {
816 return &[];
817 }
818 slice::from_raw_parts(ptr, self.last_output_elements)
819 }
820 }
821
822 // ── Helper API ────────────────────────────────────────────────────────
823
824 /// High-level helper: evaluate (decode) all chunks in sequence.
825 ///
826 /// * Text chunks are decoded via `llama_decode`.
827 /// * Image/audio chunks are first encoded with `mtmd_encode_chunk` and
828 /// then decoded via `llama_decode`.
829 ///
830 /// On success `new_n_past` is updated with the new past position.
831 ///
832 /// This call is **NOT thread-safe**.
833 ///
834 /// # Parameters
835 ///
836 /// * `lctx` – raw pointer to the llama context (from [`LlamaContext::as_ptr`])
837 /// * `chunks` – the tokenized chunks to evaluate
838 /// * `n_past` – current KV-cache position
839 /// * `seq_id` – sequence ID
840 /// * `n_batch` – maximum batch size (must be ≥ 1)
841 /// * `logits_last` – if `true`, compute logits only for the final token
842 /// * `new_n_past` – updated KV-cache position after the call
843 ///
844 /// # Errors
845 ///
846 /// Returns [`MtmdError::EvalError`] if evaluation fails.
847 #[allow(clippy::too_many_arguments)]
848 pub fn eval_chunks(
849 &mut self,
850 lctx: &mut crate::context::LlamaContext<'_>,
851 chunks: &MtmdInputChunks,
852 n_past: i32,
853 seq_id: i32,
854 n_batch: i32,
855 logits_last: bool,
856 new_n_past: &mut i32,
857 ) -> Result<()> {
858 // SAFETY: both contexts are live and non-null — the mtmd one
859 // through `&self`, the llama one through an exclusive `&mut`
860 // borrow, which is what makes decoding into it sound. The
861 // remaining arguments are scalars llama.cpp range-checks, and
862 // `new_n_past` is a caller-owned `i32` written through.
863 let ret = unsafe {
864 sys::mtmd_helper_eval_chunks(
865 self.ptr.as_ptr(),
866 lctx.context.as_ptr(),
867 chunks.ptr.as_ptr(),
868 n_past,
869 seq_id,
870 n_batch,
871 logits_last,
872 new_n_past,
873 )
874 };
875 // These encode chunks internally, so the output buffer no longer
876 // matches what `encode_chunk` last recorded — and the chunk sizes are
877 // not visible from here. Forget the length rather than hand out a
878 // slice sized for a different chunk; `output_embd` then reports empty.
879 self.last_output_elements = 0;
880 if ret != 0 {
881 return Err(MtmdError::EvalError(ret));
882 }
883 Ok(())
884 }
885
886 /// High-level helper: evaluate a single chunk.
887 ///
888 /// Works identically to [`eval_chunks`](Self::eval_chunks) but operates on
889 /// one chunk at a time.
890 ///
891 /// # Errors
892 ///
893 /// Returns [`MtmdError::EvalError`] if evaluation fails.
894 #[allow(clippy::too_many_arguments)]
895 pub fn eval_chunk_single(
896 &mut self,
897 lctx: &mut crate::context::LlamaContext<'_>,
898 chunk: &MtmdInputChunk<'_>,
899 n_past: i32,
900 seq_id: i32,
901 n_batch: i32,
902 logits_last: bool,
903 new_n_past: &mut i32,
904 ) -> Result<()> {
905 // SAFETY: both contexts are live and non-null — the mtmd one
906 // through `&self`, the llama one through an exclusive `&mut`
907 // borrow, which is what makes decoding into it sound. The
908 // remaining arguments are scalars llama.cpp range-checks, and
909 // `new_n_past` is a caller-owned `i32` written through.
910 let ret = unsafe {
911 sys::mtmd_helper_eval_chunk_single(
912 self.ptr.as_ptr(),
913 lctx.context.as_ptr(),
914 chunk.ptr,
915 n_past,
916 seq_id,
917 n_batch,
918 logits_last,
919 new_n_past,
920 )
921 };
922 // These encode chunks internally, so the output buffer no longer
923 // matches what `encode_chunk` last recorded — and the chunk sizes are
924 // not visible from here. Forget the length rather than hand out a
925 // slice sized for a different chunk; `output_embd` then reports empty.
926 self.last_output_elements = 0;
927 if ret != 0 {
928 return Err(MtmdError::EvalError(ret));
929 }
930 Ok(())
931 }
932
933 /// Decode an image/audio chunk whose embeddings have already been
934 /// computed (e.g. via [`encode_chunk`](Self::encode_chunk) followed by
935 /// [`output_embd`](Self::output_embd)).
936 ///
937 /// Unlike [`eval_chunk_single`](Self::eval_chunk_single), this helper
938 /// handles batching plus the non-causal-attention setup required by
939 /// some models (e.g. Gemma 3, Gemma 4 audio) and the M-RoPE position
940 /// layout. Use it when the embeddings are already in hand and you want
941 /// the helper to take care of `llama_decode` plumbing.
942 ///
943 /// `encoded_embd` must contain `mtmd_image_tokens_get_n_tokens(chunk) *
944 /// llama_model_n_embd_inp(model)` `f32` elements. This call is **NOT
945 /// thread-safe**.
946 ///
947 /// # Errors
948 ///
949 /// Returns [`MtmdError::EvalError`] with code `-1` if `chunk` is not an
950 /// image/audio chunk, or `1` if `llama_decode` fails.
951 #[allow(clippy::too_many_arguments)]
952 pub fn decode_image_chunk(
953 &mut self,
954 lctx: &mut crate::context::LlamaContext<'_>,
955 chunk: &MtmdInputChunk<'_>,
956 encoded_embd: &[f32],
957 n_past: i32,
958 seq_id: i32,
959 n_batch: i32,
960 new_n_past: &mut i32,
961 ) -> Result<()> {
962 // SAFETY: both contexts are live and non-null — the mtmd one
963 // through `&self`, the llama one through an exclusive `&mut`
964 // borrow, which is what makes decoding into it sound. The
965 // remaining arguments are scalars llama.cpp range-checks, and
966 // `new_n_past` is a caller-owned `i32` written through.
967 let ret = unsafe {
968 sys::mtmd_helper_decode_image_chunk(
969 self.ptr.as_ptr(),
970 lctx.context.as_ptr(),
971 chunk.ptr,
972 encoded_embd.as_ptr().cast_mut(),
973 n_past,
974 seq_id,
975 n_batch,
976 new_n_past,
977 // No post-decode callback; preserves prior single-shot behavior.
978 None,
979 std::ptr::null_mut(),
980 )
981 };
982 // These encode chunks internally, so the output buffer no longer
983 // matches what `encode_chunk` last recorded — and the chunk sizes are
984 // not visible from here. Forget the length rather than hand out a
985 // slice sized for a different chunk; `output_embd` then reports empty.
986 self.last_output_elements = 0;
987 if ret != 0 {
988 return Err(MtmdError::EvalError(ret));
989 }
990 Ok(())
991 }
992
993 /// Returns a raw pointer to the underlying `mtmd_context`.
994 ///
995 /// # Safety
996 ///
997 /// The returned pointer is valid for the lifetime of this `MtmdContext`.
998 /// The caller must not free it.
999 #[must_use]
1000 pub fn as_ptr(&self) -> *mut sys::mtmd_context {
1001 self.ptr.as_ptr()
1002 }
1003}
1004
1005// ─────────────────────────────────────────────────────────────────────────────
1006// MtmdInputText
1007// ─────────────────────────────────────────────────────────────────────────────
1008
1009/// Text input for [`MtmdContext::tokenize`].
1010///
1011/// The prompt string must contain the media marker (see
1012/// [`MtmdContext::default_marker`]) once for every bitmap to be embedded.
1013///
1014/// The prompt is passed to llama.cpp as an explicit pointer + length
1015/// (`mtmd_input_text::text_len`), so interior NUL bytes are preserved rather
1016/// than truncating the prompt — use [`MtmdInputText::from_bytes`] when the
1017/// prompt is not guaranteed NUL-free.
1018#[derive(Debug)]
1019pub struct MtmdInputText<'a> {
1020 /// Prompt bytes followed by a trailing NUL sentinel. The sentinel keeps the
1021 /// buffer usable by any C code that still treats `text` as a C string; it is
1022 /// excluded from `text_len`.
1023 text: Vec<u8>,
1024 /// Prompt length in bytes, excluding the trailing NUL sentinel. Passed
1025 /// verbatim as `mtmd_input_text::text_len`, so interior NULs are honoured.
1026 text_len: usize,
1027 add_special: bool,
1028 parse_special: bool,
1029 _marker: std::marker::PhantomData<&'a ()>,
1030}
1031
1032impl<'a> MtmdInputText<'a> {
1033 /// Borrow this as the C struct.
1034 ///
1035 /// The result points into `self`, so it must not outlive it.
1036 pub(crate) fn as_raw(&self) -> sys::mtmd_input_text {
1037 sys::mtmd_input_text {
1038 // Upstream reads exactly `text_len` bytes, so interior NULs survive.
1039 text: self.text.as_ptr().cast(),
1040 text_len: self.text_len,
1041 add_special: self.add_special,
1042 parse_special: self.parse_special,
1043 }
1044 }
1045
1046 /// Create a new `MtmdInputText` from a string prompt.
1047 ///
1048 /// * `text` – the prompt (interior NUL bytes are permitted and
1049 /// preserved)
1050 /// * `add_special` – whether to add BOS/EOS tokens
1051 /// * `parse_special` – whether to parse special tokens embedded in the text
1052 #[must_use]
1053 pub fn new(text: &'a str, add_special: bool, parse_special: bool) -> Self {
1054 Self::from_bytes(text.as_bytes(), add_special, parse_special)
1055 }
1056
1057 /// Create a new `MtmdInputText` from raw prompt bytes.
1058 ///
1059 /// Unlike a C string, the prompt length is carried explicitly, so `text`
1060 /// may contain interior NUL bytes without truncating the prompt. The bytes
1061 /// are copied into an owned, NUL-terminated buffer.
1062 ///
1063 /// * `text` – the prompt bytes (typically UTF-8)
1064 /// * `add_special` – whether to add BOS/EOS tokens
1065 /// * `parse_special` – whether to parse special tokens embedded in the text
1066 #[must_use]
1067 pub fn from_bytes(text: &'a [u8], add_special: bool, parse_special: bool) -> Self {
1068 let text_len = text.len();
1069 let mut buf = Vec::with_capacity(text_len + 1);
1070 buf.extend_from_slice(text);
1071 buf.push(0); // NUL sentinel, not counted in `text_len`
1072 Self {
1073 text: buf,
1074 text_len,
1075 add_special,
1076 parse_special,
1077 _marker: std::marker::PhantomData,
1078 }
1079 }
1080
1081 /// Try to create a new `MtmdInputText` from a string prompt.
1082 ///
1083 /// Retained for backwards compatibility. Interior NUL bytes are now
1084 /// permitted (see [`MtmdInputText::new`]), so this never returns `Err`;
1085 /// prefer [`new`](MtmdInputText::new).
1086 ///
1087 /// # Errors
1088 ///
1089 /// Never returns an error; the `Result` is kept for API stability.
1090 pub fn try_new(
1091 text: &'a str,
1092 add_special: bool,
1093 parse_special: bool,
1094 ) -> std::result::Result<Self, std::ffi::NulError> {
1095 Ok(Self::new(text, add_special, parse_special))
1096 }
1097}
1098
1099// ─────────────────────────────────────────────────────────────────────────────
1100// MtmdBitmap
1101// ─────────────────────────────────────────────────────────────────────────────
1102
1103/// An image or audio bitmap ready for multimodal encoding.
1104///
1105/// # Image bitmaps
1106///
1107/// The raw pixel data must be in RGBRGBRGB… (interleaved) format. The total
1108/// number of bytes must be `nx * ny * 3`.
1109///
1110/// # Audio bitmaps
1111///
1112/// The raw sample data must be little-endian `f32` PCM samples. The total
1113/// number of bytes must be `n_samples * 4`.
1114pub struct MtmdBitmap {
1115 ptr: NonNull<sys::mtmd_bitmap>,
1116}
1117
1118// SAFETY: a bitmap owns its `mtmd_bitmap` outright and nothing in it is tied
1119// to the creating thread.
1120unsafe impl Send for MtmdBitmap {}
1121// SAFETY: every method that mutates a bitmap takes `&mut self`, so a shared
1122// reference reaches only reads.
1123unsafe impl Sync for MtmdBitmap {}
1124
1125impl std::fmt::Debug for MtmdBitmap {
1126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1127 f.debug_struct("MtmdBitmap")
1128 .field("nx", &self.nx())
1129 .field("ny", &self.ny())
1130 .field("n_bytes", &self.n_bytes())
1131 .field("is_audio", &self.is_audio())
1132 .finish()
1133 }
1134}
1135
1136impl Drop for MtmdBitmap {
1137 fn drop(&mut self) {
1138 // SAFETY: this runs once from `Drop`, the handle is non-null, and nothing
1139 // reads it afterwards.
1140 unsafe { sys::mtmd_bitmap_free(self.ptr.as_ptr()) }
1141 }
1142}
1143
1144impl MtmdBitmap {
1145 /// Create a bitmap from raw RGB pixel data.
1146 ///
1147 /// * `nx` – image width in pixels
1148 /// * `ny` – image height in pixels
1149 /// * `data` – raw pixel bytes in RGBRGB… format; must be `nx * ny * 3` bytes
1150 ///
1151 /// # Errors
1152 ///
1153 /// Returns [`MtmdError::BitmapCreateFailed`] if the underlying C call
1154 /// returns null.
1155 pub fn from_rgb(nx: u32, ny: u32, data: &[u8]) -> Result<Self> {
1156 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
1157 // and the model/context handles are borrowed — and the result is checked
1158 // for null before being wrapped.
1159 let ptr = unsafe { sys::mtmd_bitmap_init(nx, ny, data.as_ptr()) };
1160 let ptr = NonNull::new(ptr).ok_or(MtmdError::BitmapCreateFailed)?;
1161 Ok(Self { ptr })
1162 }
1163
1164 /// Create an audio bitmap from PCM `f32` samples.
1165 ///
1166 /// * `samples` – slice of PCM float samples
1167 ///
1168 /// # Errors
1169 ///
1170 /// Returns [`MtmdError::BitmapCreateFailed`] if the underlying C call
1171 /// returns null.
1172 pub fn from_audio(samples: &[f32]) -> Result<Self> {
1173 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
1174 // and the model/context handles are borrowed — and the result is checked
1175 // for null before being wrapped.
1176 let ptr = unsafe { sys::mtmd_bitmap_init_from_audio(samples.len(), samples.as_ptr()) };
1177 let ptr = NonNull::new(ptr).ok_or(MtmdError::BitmapCreateFailed)?;
1178 Ok(Self { ptr })
1179 }
1180
1181 /// Build an `MtmdBitmap` from a `mtmd_helper_bitmap_wrapper`, taking
1182 /// ownership of the `bitmap` and freeing any `video_ctx`.
1183 ///
1184 /// The `from_file`/`from_buf` constructors only support image/audio input.
1185 /// When the input is a video the helper returns a non-null `video_ctx`
1186 /// (an open ffmpeg stream) which is not representable as an `MtmdBitmap`;
1187 /// we free it here to avoid leaking it. Use [`MtmdVideo`] for video input.
1188 fn from_wrapper(wrapper: sys::mtmd_helper_bitmap_wrapper) -> Result<Self> {
1189 if !wrapper.video_ctx.is_null() {
1190 // SAFETY: this runs once from `Drop`, the handle is non-null, and nothing
1191 // reads it afterwards.
1192 unsafe { sys::mtmd_helper_video_free(wrapper.video_ctx) };
1193 }
1194 let ptr = NonNull::new(wrapper.bitmap).ok_or(MtmdError::BitmapCreateFailed)?;
1195 Ok(Self { ptr })
1196 }
1197
1198 /// Load a bitmap from a file (image or audio).
1199 ///
1200 /// Supported image formats: JPEG, PNG, BMP, GIF, and others handled by
1201 /// `stb_image`. Supported audio formats: WAV, MP3, FLAC (via miniaudio).
1202 ///
1203 /// # Errors
1204 ///
1205 /// Returns [`MtmdError::BitmapCreateFailed`] if the file cannot be loaded.
1206 pub fn from_file(ctx: &MtmdContext, path: impl AsRef<Path>) -> Result<Self> {
1207 let path = path.as_ref().to_str().ok_or(MtmdError::PathNotUtf8)?;
1208 let c_path = CString::new(path)?;
1209
1210 // `placeholder = false`: load the real bitmap data (not a token-count
1211 // placeholder). For image/audio the returned `video_ctx` is always null.
1212 // SAFETY: the context handle and the `CString` path are both alive for
1213 // the call, and `mtmd_helper_init_opt_default()` returns an options
1214 // struct by value. The result is checked before being wrapped.
1215 let wrapper = unsafe {
1216 sys::mtmd_helper_bitmap_init_from_file(
1217 ctx.ptr.as_ptr(),
1218 c_path.as_ptr(),
1219 false,
1220 sys::mtmd_helper_init_opt_default(),
1221 )
1222 };
1223 Self::from_wrapper(wrapper)
1224 }
1225
1226 /// Load a bitmap from an in-memory buffer containing a file.
1227 ///
1228 /// The format is auto-detected (image vs audio via magic bytes).
1229 ///
1230 /// # Errors
1231 ///
1232 /// Returns [`MtmdError::BitmapCreateFailed`] if decoding fails.
1233 pub fn from_buf(ctx: &MtmdContext, buf: &[u8]) -> Result<Self> {
1234 // `placeholder = false`: load the real bitmap data (not a token-count
1235 // placeholder). For image/audio the returned `video_ctx` is always null.
1236 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
1237 // and the model/context handles are borrowed — and the result is checked
1238 // for null before being wrapped.
1239 let wrapper = unsafe {
1240 sys::mtmd_helper_bitmap_init_from_buf(
1241 ctx.ptr.as_ptr(),
1242 buf.as_ptr(),
1243 buf.len(),
1244 false,
1245 sys::mtmd_helper_init_opt_default(),
1246 )
1247 };
1248 Self::from_wrapper(wrapper)
1249 }
1250
1251 /// Mark this bitmap as mergeable with an adjacent mergeable bitmap.
1252 ///
1253 /// Video-capable models such as Qwen-VL merge consecutive frames into one
1254 /// chunk (a temporal merge). [`MtmdVideo::read_next`] already sets this on
1255 /// the frames it produces; you only need it when you build frames yourself
1256 /// with [`Self::from_rgb`] and expect them to merge. Without it each frame
1257 /// becomes its own chunk, which costs tokens and loses temporal structure.
1258 ///
1259 /// Wraps `mtmd_bitmap_set_mergeable`.
1260 pub fn set_mergeable(&mut self, mergeable: bool) {
1261 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1262 // remaining arguments are scalars or pointers valid for the call.
1263 unsafe { sys::mtmd_bitmap_set_mergeable(self.ptr.as_ptr(), mergeable) }
1264 }
1265
1266 /// Mark this bitmap as a video frame rather than a still image.
1267 ///
1268 /// A video-capable model needs **both** this and
1269 /// [`set_mergeable`](Self::set_mergeable) on *every* frame; one without the
1270 /// other does not get you a merged video chunk. As with `set_mergeable`,
1271 /// [`MtmdVideo::read_next`] already sets both on the frames it produces —
1272 /// this is for frames you build yourself with [`Self::from_rgb`].
1273 ///
1274 /// New in `b12032`, which split the flag out so a caller can mark frames
1275 /// that did not come from the video reader.
1276 ///
1277 /// Wraps `mtmd_bitmap_set_is_video`.
1278 pub fn set_is_video(&mut self, is_video: bool) {
1279 // SAFETY: a live `&mut self` gives an exclusive, non-null bitmap; the
1280 // call only flips a flag on it.
1281 unsafe { sys::mtmd_bitmap_set_is_video(self.ptr.as_ptr(), is_video) }
1282 }
1283
1284 // ── Getters ───────────────────────────────────────────────────────────
1285
1286 /// Width in pixels (for images) or 0 (for audio).
1287 #[must_use]
1288 pub fn nx(&self) -> u32 {
1289 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1290 // remaining arguments are scalars or pointers valid for the call.
1291 unsafe { sys::mtmd_bitmap_get_nx(self.ptr.as_ptr()) }
1292 }
1293
1294 /// Height in pixels (for images) or 0 (for audio).
1295 #[must_use]
1296 pub fn ny(&self) -> u32 {
1297 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1298 // remaining arguments are scalars or pointers valid for the call.
1299 unsafe { sys::mtmd_bitmap_get_ny(self.ptr.as_ptr()) }
1300 }
1301
1302 /// Total number of bytes in the bitmap data.
1303 #[must_use]
1304 pub fn n_bytes(&self) -> usize {
1305 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1306 // remaining arguments are scalars or pointers valid for the call.
1307 unsafe { sys::mtmd_bitmap_get_n_bytes(self.ptr.as_ptr()) }
1308 }
1309
1310 /// Returns `true` if this bitmap contains audio (rather than image) data.
1311 #[must_use]
1312 pub fn is_audio(&self) -> bool {
1313 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1314 // remaining arguments are scalars or pointers valid for the call.
1315 unsafe { sys::mtmd_bitmap_is_audio(self.ptr.as_ptr()) }
1316 }
1317
1318 /// Return the raw pixel / sample data.
1319 #[must_use]
1320 pub fn data(&self) -> &[u8] {
1321 let n = self.n_bytes();
1322 if n == 0 {
1323 return &[];
1324 }
1325 // SAFETY: a read through a live, non-null bitmap handle.
1326 let ptr = unsafe { sys::mtmd_bitmap_get_data(self.ptr.as_ptr()) };
1327 // SAFETY: `n` is this bitmap's own `n_bytes()`, which is exactly how
1328 // many bytes upstream allocated for the buffer `ptr` points at, and
1329 // the borrow is tied to `&self`.
1330 unsafe { slice::from_raw_parts(ptr, n) }
1331 }
1332
1333 /// Return the optional ID string attached to this bitmap (used for KV
1334 /// cache tracking), or `None` if no ID has been set.
1335 #[must_use]
1336 pub fn id(&self) -> Option<&str> {
1337 // SAFETY: a read through a live handle (or no handle at all, for the
1338 // library-wide accessors); the returned pointer is only converted
1339 // below, never freed here.
1340 let ptr = unsafe { sys::mtmd_bitmap_get_id(self.ptr.as_ptr()) };
1341 if ptr.is_null() {
1342 return None;
1343 }
1344 // SAFETY: the pointer comes from an mtmd accessor, which returns a static or
1345 // handle-owned NUL-terminated string that outlives the borrow taken here.
1346 unsafe { CStr::from_ptr(ptr) }.to_str().ok()
1347 }
1348
1349 /// Attach an optional ID string to this bitmap (used for KV cache
1350 /// tracking).
1351 ///
1352 /// # Errors
1353 ///
1354 /// Returns an error if `id` contains an interior NUL byte.
1355 pub fn set_id(&mut self, id: &str) -> std::result::Result<(), std::ffi::NulError> {
1356 let cs = CString::new(id)?;
1357 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1358 // remaining arguments are scalars or pointers valid for the call.
1359 unsafe { sys::mtmd_bitmap_set_id(self.ptr.as_ptr(), cs.as_ptr()) };
1360 Ok(())
1361 }
1362}
1363
1364// ─────────────────────────────────────────────────────────────────────────────
1365// Video input
1366// ─────────────────────────────────────────────────────────────────────────────
1367
1368// `free()` from libc — used to release the heap-allocated text returned by
1369// `mtmd_helper_video_read_next` (the C side allocates it with strdup/malloc and
1370// documents that the caller must release it with `free()`).
1371extern "C" {
1372 fn free(ptr: *mut std::os::raw::c_void);
1373 /// `strdup` from libc. Used for the text a lazy-bitmap callback yields:
1374 /// mtmd releases it with `free()`, which Rust's allocator is not
1375 /// compatible with, so the copy has to come from malloc.
1376 fn strdup(s: *const std::os::raw::c_char) -> *mut std::os::raw::c_char;
1377}
1378
1379/// Parameters controlling how a [`MtmdVideo`] stream is opened and sampled.
1380///
1381/// Obtain a default-initialised instance via [`MtmdVideoParams::default()`]
1382/// (which mirrors `mtmd_helper_video_init_params_default`: ~4 fps, native
1383/// `ffmpeg`/`ffprobe` from `PATH`, and a 5 s timestamp interval) and tweak it
1384/// with the builder methods.
1385pub struct MtmdVideoParams {
1386 params: sys::mtmd_helper_video_init_params,
1387 // Keeps the `ffmpeg_bin_dir` C string alive for as long as `params`
1388 // borrows it via a raw pointer.
1389 ffmpeg_bin_dir: Option<CString>,
1390}
1391
1392impl std::fmt::Debug for MtmdVideoParams {
1393 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1394 f.debug_struct("MtmdVideoParams")
1395 .field("fps_target", &self.params.fps_target)
1396 .field("timestamp_interval_ms", &self.params.timestamp_interval_ms)
1397 .field("ffmpeg_bin_dir", &self.ffmpeg_bin_dir)
1398 .finish()
1399 }
1400}
1401
1402impl Default for MtmdVideoParams {
1403 fn default() -> Self {
1404 // SAFETY: no pointer is involved; upstream returns a fully initialised struct by value.
1405 let params = unsafe { sys::mtmd_helper_video_init_params_default() };
1406 Self {
1407 params,
1408 ffmpeg_bin_dir: None,
1409 }
1410 }
1411}
1412
1413impl MtmdVideoParams {
1414 /// Desired output frame rate. Values `<= 0` mean "use the video's native
1415 /// fps" (the default is ~4 fps).
1416 #[must_use]
1417 pub fn fps_target(mut self, fps: f32) -> Self {
1418 self.params.fps_target = fps;
1419 self
1420 }
1421
1422 /// Interval, in milliseconds, between inserted timestamp text chunks (e.g.
1423 /// `"[10m50.5s]"`). Values `<= 0` disable timestamps (default 5000 ms).
1424 #[must_use]
1425 pub fn timestamp_interval_ms(mut self, ms: i64) -> Self {
1426 self.params.timestamp_interval_ms = ms;
1427 self
1428 }
1429
1430 /// Directory containing the `ffmpeg`/`ffprobe` binaries. Pass `None` to
1431 /// search `PATH` (the default).
1432 ///
1433 /// # Errors
1434 ///
1435 /// Returns an error if `dir` contains an interior NUL byte.
1436 pub fn ffmpeg_bin_dir(mut self, dir: Option<&str>) -> Result<Self> {
1437 match dir {
1438 None => {
1439 self.params.ffmpeg_bin_dir = std::ptr::null();
1440 self.ffmpeg_bin_dir = None;
1441 }
1442 Some(d) => {
1443 let cs = CString::new(d)?;
1444 self.params.ffmpeg_bin_dir = cs.as_ptr();
1445 // Store the owner so the pointer above stays valid.
1446 self.ffmpeg_bin_dir = Some(cs);
1447 }
1448 }
1449 Ok(self)
1450 }
1451}
1452
1453/// Metadata describing an open [`MtmdVideo`] stream.
1454#[derive(Debug, Clone, Copy, PartialEq)]
1455pub struct MtmdVideoInfo {
1456 /// Frame width in pixels.
1457 pub width: u32,
1458 /// Frame height in pixels.
1459 pub height: u32,
1460 /// Effective frames-per-second (the `fps_target` if set, else native fps).
1461 pub fps: f32,
1462 /// Estimated total frame count at the effective fps (`-1` if unknown).
1463 pub n_frames: i32,
1464}
1465
1466/// One item read from a [`MtmdVideo`] stream by [`MtmdVideo::read_next`].
1467#[derive(Debug)]
1468pub enum MtmdVideoItem {
1469 /// A decoded video frame, ready to be tokenized like any other image
1470 /// [`MtmdBitmap`].
1471 Frame(MtmdBitmap),
1472 /// A timestamp text marker (e.g. `"[10m50.5s]"`) to be inserted into the
1473 /// prompt between frames.
1474 Text(String),
1475}
1476
1477/// An open video stream, decoded frame-by-frame via `ffmpeg`.
1478///
1479/// The notion of "video" exists only at the helper level — it is decoded into
1480/// a sequence of image [frames](MtmdVideoItem::Frame) and timestamp
1481/// [text markers](MtmdVideoItem::Text) which are then fed through the normal
1482/// multimodal pipeline.
1483///
1484/// Requires a build with video support (see [`MtmdContext::supports_video`])
1485/// and `ffmpeg`/`ffprobe` available at runtime.
1486///
1487/// # Example
1488///
1489/// ```no_run
1490/// # #[cfg(feature = "mtmd")]
1491/// # fn run(mtmd_ctx: &llama_cpp_4::mtmd::MtmdContext) -> Result<(), llama_cpp_4::mtmd::MtmdError> {
1492/// use std::path::Path;
1493/// use llama_cpp_4::mtmd::{MtmdVideo, MtmdVideoParams, MtmdVideoItem};
1494///
1495/// let mut video = MtmdVideo::from_file(mtmd_ctx, Path::new("clip.mp4"),
1496/// &MtmdVideoParams::default())?;
1497/// while let Some(item) = video.read_next()? {
1498/// match item {
1499/// MtmdVideoItem::Frame(bitmap) => { /* tokenize the frame */ }
1500/// MtmdVideoItem::Text(ts) => { /* insert the timestamp marker */ }
1501/// }
1502/// }
1503/// # Ok(())
1504/// # }
1505/// ```
1506pub struct MtmdVideo {
1507 ptr: NonNull<sys::mtmd_helper_video>,
1508}
1509
1510impl std::fmt::Debug for MtmdVideo {
1511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1512 f.debug_struct("MtmdVideo")
1513 .field("info", &self.info())
1514 .finish()
1515 }
1516}
1517
1518impl Drop for MtmdVideo {
1519 fn drop(&mut self) {
1520 // SAFETY: this runs once from `Drop`, the handle is non-null, and nothing
1521 // reads it afterwards.
1522 unsafe { sys::mtmd_helper_video_free(self.ptr.as_ptr()) }
1523 }
1524}
1525
1526impl MtmdVideo {
1527 /// Open a video file for frame-by-frame decoding.
1528 ///
1529 /// # Errors
1530 ///
1531 /// Returns [`MtmdError::VideoInitFailed`] if the stream cannot be opened
1532 /// (no video support compiled in, `ffprobe` not found, file unreadable,
1533 /// …), or [`MtmdError::InvalidPath`] / [`MtmdError::PathNotUtf8`] for a bad
1534 /// path.
1535 pub fn from_file(
1536 ctx: &MtmdContext,
1537 path: impl AsRef<Path>,
1538 params: &MtmdVideoParams,
1539 ) -> Result<Self> {
1540 let path = path.as_ref().to_str().ok_or(MtmdError::PathNotUtf8)?;
1541 let c_path = CString::new(path)?;
1542 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
1543 // and the model/context handles are borrowed — and the result is checked
1544 // for null before being wrapped.
1545 let ptr = unsafe {
1546 sys::mtmd_helper_video_init(ctx.ptr.as_ptr(), c_path.as_ptr(), params.params)
1547 };
1548 let ptr = NonNull::new(ptr).ok_or(MtmdError::VideoInitFailed)?;
1549 Ok(Self { ptr })
1550 }
1551
1552 /// Open a video from an in-memory buffer. The buffer is copied internally,
1553 /// so it need not outlive this call.
1554 ///
1555 /// # Errors
1556 ///
1557 /// Returns [`MtmdError::VideoInitFailed`] if the stream cannot be opened.
1558 pub fn from_buf(ctx: &MtmdContext, buf: &[u8], params: &MtmdVideoParams) -> Result<Self> {
1559 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
1560 // and the model/context handles are borrowed — and the result is checked
1561 // for null before being wrapped.
1562 let ptr = unsafe {
1563 sys::mtmd_helper_video_init_from_buf(
1564 ctx.ptr.as_ptr(),
1565 buf.as_ptr(),
1566 buf.len(),
1567 params.params,
1568 )
1569 };
1570 let ptr = NonNull::new(ptr).ok_or(MtmdError::VideoInitFailed)?;
1571 Ok(Self { ptr })
1572 }
1573
1574 /// Return metadata (resolution, effective fps, estimated frame count) for
1575 /// this stream.
1576 #[must_use]
1577 pub fn info(&self) -> MtmdVideoInfo {
1578 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1579 // remaining arguments are scalars or pointers valid for the call.
1580 let info = unsafe { sys::mtmd_helper_video_get_info(self.ptr.as_ptr()) };
1581 MtmdVideoInfo {
1582 width: info.width,
1583 height: info.height,
1584 fps: info.fps,
1585 n_frames: info.n_frames,
1586 }
1587 }
1588
1589 /// Read the next item from the stream.
1590 ///
1591 /// Returns `Ok(Some(item))` for each frame or timestamp marker, and
1592 /// `Ok(None)` once the end of the stream is reached.
1593 ///
1594 /// # Errors
1595 ///
1596 /// Returns [`MtmdError::VideoReadError`] on a decode error.
1597 pub fn read_next(&mut self) -> Result<Option<MtmdVideoItem>> {
1598 let mut out_bitmap: *mut sys::mtmd_bitmap = std::ptr::null_mut();
1599 let mut out_text: *mut std::os::raw::c_char = std::ptr::null_mut();
1600 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1601 // remaining arguments are scalars or pointers valid for the call.
1602 let ret = unsafe {
1603 sys::mtmd_helper_video_read_next(
1604 self.ptr.as_ptr(),
1605 &raw mut out_bitmap,
1606 &raw mut out_text,
1607 )
1608 };
1609 match ret {
1610 0 => {
1611 if let Some(ptr) = NonNull::new(out_bitmap) {
1612 Ok(Some(MtmdVideoItem::Frame(MtmdBitmap { ptr })))
1613 } else if !out_text.is_null() {
1614 // SAFETY: the pointer comes from an mtmd accessor, which returns a static or
1615 // handle-owned NUL-terminated string that outlives the borrow taken here.
1616 let text = unsafe { CStr::from_ptr(out_text) }
1617 .to_string_lossy()
1618 .into_owned();
1619 // The C side allocated this with strdup/malloc; release it.
1620 // SAFETY: `out_text` was allocated by llama.cpp with `strdup`, so it must be
1621 // released with `free` rather than a Rust allocator, and it is not read
1622 // again afterwards.
1623 unsafe { free(out_text.cast()) };
1624 Ok(Some(MtmdVideoItem::Text(text)))
1625 } else {
1626 // Success but nothing produced — treat as end of stream.
1627 Ok(None)
1628 }
1629 }
1630 -1 => Ok(None), // EOF
1631 other => Err(MtmdError::VideoReadError(other)),
1632 }
1633 }
1634}
1635
1636// ─────────────────────────────────────────────────────────────────────────────
1637// MtmdInputChunks
1638// ─────────────────────────────────────────────────────────────────────────────
1639
1640/// A list of tokenized input chunks produced by [`MtmdContext::tokenize`].
1641///
1642/// Each chunk is either a text token sequence or a set of image/audio tokens.
1643pub struct MtmdInputChunks {
1644 ptr: NonNull<sys::mtmd_input_chunks>,
1645}
1646
1647impl std::fmt::Debug for MtmdInputChunks {
1648 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1649 f.debug_struct("MtmdInputChunks")
1650 .field("len", &self.len())
1651 .finish()
1652 }
1653}
1654
1655impl Drop for MtmdInputChunks {
1656 fn drop(&mut self) {
1657 // SAFETY: this runs once from `Drop`, the handle is non-null, and nothing
1658 // reads it afterwards.
1659 unsafe { sys::mtmd_input_chunks_free(self.ptr.as_ptr()) }
1660 }
1661}
1662
1663impl MtmdInputChunks {
1664 /// Create a new, empty chunk list. Populated by
1665 /// [`MtmdContext::tokenize`].
1666 ///
1667 /// # Panics
1668 ///
1669 /// Panics if the underlying C allocation fails (OOM).
1670 #[must_use]
1671 pub fn new() -> Self {
1672 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
1673 // and the model/context handles are borrowed — and the result is checked
1674 // for null before being wrapped.
1675 let ptr = unsafe { sys::mtmd_input_chunks_init() };
1676 let ptr = NonNull::new(ptr).expect("mtmd_input_chunks_init returned null");
1677 Self { ptr }
1678 }
1679
1680 /// Number of chunks in this list.
1681 #[must_use]
1682 pub fn len(&self) -> usize {
1683 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1684 // remaining arguments are scalars or pointers valid for the call.
1685 unsafe { sys::mtmd_input_chunks_size(self.ptr.as_ptr()) }
1686 }
1687
1688 /// Restore a chunk previously serialized with
1689 /// [`MtmdInputChunk::save`], returning it as an owned placeholder.
1690 ///
1691 /// The result carries only metadata — token count, position count, type —
1692 /// so it can line a restored KV cache up with the prompt that produced it.
1693 /// It cannot be re-encoded; the pixels are gone.
1694 ///
1695 /// Wraps `mtmd_input_chunk_load`.
1696 ///
1697 /// # Errors
1698 ///
1699 /// Returns [`MtmdError::ChunkLoadFailed`] if the buffer is not a chunk
1700 /// this build can restore.
1701 pub fn load_chunk(buf: &[u8]) -> Result<OwnedMtmdInputChunk> {
1702 // SAFETY: `buf` is a Rust slice whose pointer and length are passed together,
1703 // so the read stays in bounds; the result is checked for null below.
1704 let ptr = unsafe {
1705 sys::mtmd_input_chunk_load(buf.as_ptr().cast::<std::os::raw::c_char>(), buf.len())
1706 };
1707 NonNull::new(ptr)
1708 .map(|ptr| OwnedMtmdInputChunk { ptr })
1709 .ok_or(MtmdError::ChunkLoadFailed)
1710 }
1711
1712 /// Returns `true` if there are no chunks.
1713 #[must_use]
1714 pub fn is_empty(&self) -> bool {
1715 self.len() == 0
1716 }
1717
1718 /// Get the `idx`-th chunk. Returns `None` if `idx >= len()`.
1719 #[must_use]
1720 pub fn get(&self, idx: usize) -> Option<MtmdInputChunk<'_>> {
1721 if idx >= self.len() {
1722 return None;
1723 }
1724 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1725 // remaining arguments are scalars or pointers valid for the call.
1726 let ptr = unsafe { sys::mtmd_input_chunks_get(self.ptr.as_ptr(), idx) };
1727 if ptr.is_null() {
1728 return None;
1729 }
1730 Some(MtmdInputChunk {
1731 ptr,
1732 _marker: std::marker::PhantomData,
1733 })
1734 }
1735
1736 /// Iterate over all chunks.
1737 pub fn iter(&self) -> impl Iterator<Item = MtmdInputChunk<'_>> {
1738 (0..self.len()).filter_map(|i| self.get(i))
1739 }
1740
1741 /// Total number of tokens across all chunks.
1742 ///
1743 /// Equivalent to `mtmd_helper_get_n_tokens`.
1744 #[must_use]
1745 pub fn n_tokens(&self) -> usize {
1746 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1747 // remaining arguments are scalars or pointers valid for the call.
1748 unsafe { sys::mtmd_helper_get_n_tokens(self.ptr.as_ptr()) }
1749 }
1750
1751 /// Total number of *positions* across all chunks (used for KV-cache
1752 /// tracking with M-RoPE models where positions ≠ tokens).
1753 ///
1754 /// Equivalent to `mtmd_helper_get_n_pos`.
1755 #[must_use]
1756 pub fn n_pos(&self) -> i32 {
1757 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1758 // remaining arguments are scalars or pointers valid for the call.
1759 unsafe { sys::mtmd_helper_get_n_pos(self.ptr.as_ptr()) }
1760 }
1761}
1762
1763impl Default for MtmdInputChunks {
1764 fn default() -> Self {
1765 Self::new()
1766 }
1767}
1768
1769// ─────────────────────────────────────────────────────────────────────────────
1770// MtmdInputChunkType
1771// ─────────────────────────────────────────────────────────────────────────────
1772
1773/// The type of an [`MtmdInputChunk`].
1774#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1775pub enum MtmdInputChunkType {
1776 /// Plain text tokens.
1777 Text,
1778 /// Image tokens (embeddings produced by the vision encoder).
1779 Image,
1780 /// Audio tokens (embeddings produced by the audio encoder).
1781 Audio,
1782}
1783
1784impl From<sys::mtmd_input_chunk_type> for MtmdInputChunkType {
1785 fn from(v: sys::mtmd_input_chunk_type) -> Self {
1786 // mtmd_input_chunk_type is a plain C `typedef unsigned int`.
1787 // The variants are exported as free-standing constants.
1788 if v == sys::MTMD_INPUT_CHUNK_TYPE_IMAGE {
1789 Self::Image
1790 } else if v == sys::MTMD_INPUT_CHUNK_TYPE_AUDIO {
1791 Self::Audio
1792 } else {
1793 Self::Text
1794 }
1795 }
1796}
1797
1798// ─────────────────────────────────────────────────────────────────────────────
1799// MtmdInputChunk
1800// ─────────────────────────────────────────────────────────────────────────────
1801
1802/// A single tokenized input chunk (text, image, or audio).
1803///
1804/// Instances are borrowed from an [`MtmdInputChunks`] list and live as long
1805/// as that list.
1806#[derive(Debug)]
1807pub struct MtmdInputChunk<'chunks> {
1808 ptr: *const sys::mtmd_input_chunk,
1809 _marker: std::marker::PhantomData<&'chunks MtmdInputChunks>,
1810}
1811
1812impl<'chunks> MtmdInputChunk<'chunks> {
1813 /// The type of this chunk.
1814 #[must_use]
1815 pub fn chunk_type(&self) -> MtmdInputChunkType {
1816 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1817 // remaining arguments are scalars or pointers valid for the call.
1818 let t = unsafe { sys::mtmd_input_chunk_get_type(self.ptr) };
1819 MtmdInputChunkType::from(t)
1820 }
1821
1822 /// Total number of tokens in this chunk.
1823 #[must_use]
1824 pub fn n_tokens(&self) -> usize {
1825 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1826 // remaining arguments are scalars or pointers valid for the call.
1827 unsafe { sys::mtmd_input_chunk_get_n_tokens(self.ptr) }
1828 }
1829
1830 /// Number of temporal positions (equals `n_tokens` for non-M-RoPE models).
1831 #[must_use]
1832 pub fn n_pos(&self) -> i32 {
1833 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1834 // remaining arguments are scalars or pointers valid for the call.
1835 unsafe { sys::mtmd_input_chunk_get_n_pos(self.ptr) }
1836 }
1837
1838 /// Serialize this chunk's metadata to a byte buffer.
1839 ///
1840 /// Only metadata is saved — never the image or audio payload. A chunk
1841 /// restored with [`MtmdInputChunks::load_chunk`] is a *placeholder*: it
1842 /// carries the token and position counts needed to line a cached KV state
1843 /// back up with its prompt, but cannot be re-encoded. That is the intended
1844 /// use, and it is why this is cheap enough to store alongside a session
1845 /// file written by
1846 /// [`state_seq_save_file`](crate::context::LlamaContext::state_seq_save_file).
1847 ///
1848 /// Wraps `mtmd_input_chunk_save`.
1849 ///
1850 /// # Errors
1851 ///
1852 /// Returns [`MtmdError::ChunkSaveFailed`] if llama.cpp cannot serialize
1853 /// this chunk.
1854 pub fn save(&self) -> Result<Vec<u8>> {
1855 // Two-call protocol: query the length, then fill.
1856 let mut needed: usize = 0;
1857 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1858 // remaining arguments are scalars or pointers valid for the call.
1859 let rc = unsafe {
1860 sys::mtmd_input_chunk_save(self.ptr, std::ptr::null_mut(), 0, &raw mut needed)
1861 };
1862 if rc != 0 && needed == 0 {
1863 return Err(MtmdError::ChunkSaveFailed(rc));
1864 }
1865 let mut buf = vec![0u8; needed];
1866 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1867 // remaining arguments are scalars or pointers valid for the call.
1868 let rc = unsafe {
1869 sys::mtmd_input_chunk_save(
1870 self.ptr,
1871 buf.as_mut_ptr().cast::<std::os::raw::c_char>(),
1872 buf.len(),
1873 &raw mut needed,
1874 )
1875 };
1876 if rc != 0 {
1877 return Err(MtmdError::ChunkSaveFailed(rc));
1878 }
1879 buf.truncate(needed);
1880 Ok(buf)
1881 }
1882
1883 /// Copy this chunk, payload and all, into an owned handle.
1884 ///
1885 /// [`MtmdInputChunk`] borrows from the [`MtmdInputChunks`] list holding it,
1886 /// so it dies with that list. Take a copy when a chunk has to outlive the
1887 /// tokenization it came from — caching encoded media across requests, for
1888 /// instance. Unlike [`Self::to_placeholder`], the result is still usable
1889 /// for encoding.
1890 ///
1891 /// Wraps `mtmd_input_chunk_copy`.
1892 ///
1893 /// # Errors
1894 ///
1895 /// Returns [`MtmdError::ChunkLoadFailed`] if llama.cpp returns null.
1896 pub fn to_owned_chunk(&self) -> Result<OwnedMtmdInputChunk> {
1897 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1898 // remaining arguments are scalars or pointers valid for the call.
1899 let ptr = unsafe { sys::mtmd_input_chunk_copy(self.ptr) };
1900 NonNull::new(ptr)
1901 .map(|ptr| OwnedMtmdInputChunk { ptr })
1902 .ok_or(MtmdError::ChunkLoadFailed)
1903 }
1904
1905 /// Copy this chunk as a standalone placeholder — metadata only, no payload.
1906 ///
1907 /// Same shape as a round trip through [`Self::save`] and
1908 /// [`MtmdInputChunks::load_chunk`], without the serialization. Useful for
1909 /// keeping a prompt's structure alive after the pixels have been dropped.
1910 ///
1911 /// Wraps `mtmd_input_chunk_get_placeholder`.
1912 ///
1913 /// # Errors
1914 ///
1915 /// Returns [`MtmdError::ChunkLoadFailed`] if llama.cpp returns null.
1916 pub fn to_placeholder(&self) -> Result<OwnedMtmdInputChunk> {
1917 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1918 // remaining arguments are scalars or pointers valid for the call.
1919 let ptr = unsafe { sys::mtmd_input_chunk_get_placeholder(self.ptr) };
1920 NonNull::new(ptr)
1921 .map(|ptr| OwnedMtmdInputChunk { ptr })
1922 .ok_or(MtmdError::ChunkLoadFailed)
1923 }
1924
1925 /// Return the raw llama token IDs for a **text** chunk.
1926 ///
1927 /// Returns `None` if this chunk is not a text chunk.
1928 #[must_use]
1929 pub fn text_tokens(&self) -> Option<&[i32]> {
1930 if self.chunk_type() != MtmdInputChunkType::Text {
1931 return None;
1932 }
1933 let mut n: usize = 0;
1934 // SAFETY: a read through a live chunk; upstream writes the token count
1935 // through `n` and returns a pointer into the chunk's own storage.
1936 let ptr = unsafe { sys::mtmd_input_chunk_get_tokens_text(self.ptr, &raw mut n) };
1937 if ptr.is_null() || n == 0 {
1938 return Some(&[]);
1939 }
1940 // SAFETY: `ptr` is non-null (checked above) and `n` is the count upstream
1941 // just wrote for this same buffer.
1942 Some(unsafe { slice::from_raw_parts(ptr, n) })
1943 }
1944
1945 /// Return the image token metadata for an **image** or **audio** chunk.
1946 ///
1947 /// Returns `None` for text chunks.
1948 #[must_use]
1949 pub fn image_tokens(&self) -> Option<MtmdImageTokens<'chunks>> {
1950 match self.chunk_type() {
1951 MtmdInputChunkType::Image | MtmdInputChunkType::Audio => {}
1952 MtmdInputChunkType::Text => return None,
1953 }
1954 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
1955 // remaining arguments are scalars or pointers valid for the call.
1956 let ptr = unsafe { sys::mtmd_input_chunk_get_tokens_image(self.ptr) };
1957 if ptr.is_null() {
1958 return None;
1959 }
1960 Some(MtmdImageTokens {
1961 ptr,
1962 _marker: std::marker::PhantomData,
1963 })
1964 }
1965
1966 /// Optional ID attached to this chunk (used for KV cache tracking).
1967 #[must_use]
1968 pub fn id(&self) -> Option<&str> {
1969 // SAFETY: a read through a live handle (or no handle at all, for the
1970 // library-wide accessors); the returned pointer is only converted
1971 // below, never freed here.
1972 let ptr = unsafe { sys::mtmd_input_chunk_get_id(self.ptr) };
1973 if ptr.is_null() {
1974 return None;
1975 }
1976 // SAFETY: the pointer comes from an mtmd accessor, which returns a static or
1977 // handle-owned NUL-terminated string that outlives the borrow taken here.
1978 unsafe { CStr::from_ptr(ptr) }.to_str().ok()
1979 }
1980
1981 /// Returns the raw `*const mtmd_input_chunk` pointer.
1982 ///
1983 /// # Safety
1984 ///
1985 /// The returned pointer is valid for the lifetime of the parent
1986 /// `MtmdInputChunks`.
1987 #[must_use]
1988 pub fn as_ptr(&self) -> *const sys::mtmd_input_chunk {
1989 self.ptr
1990 }
1991}
1992
1993// ─────────────────────────────────────────────────────────────────────────────
1994// MtmdDecoderPos
1995// ─────────────────────────────────────────────────────────────────────────────
1996
1997/// Per-token position used by M-RoPE decoder attention.
1998///
1999/// `t` is the temporal axis, `x`/`y` the spatial axes. `z` is reserved for
2000/// future use. Values are *relative* to a base `pos_0` provided when the
2001/// position is computed.
2002#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2003#[repr(C)]
2004pub struct MtmdDecoderPos {
2005 /// Temporal index.
2006 pub t: u32,
2007 /// Spatial X.
2008 pub x: u32,
2009 /// Spatial Y.
2010 pub y: u32,
2011 /// Reserved.
2012 pub z: u32,
2013}
2014
2015// ─────────────────────────────────────────────────────────────────────────────
2016// MtmdImageTokens
2017// ─────────────────────────────────────────────────────────────────────────────
2018
2019/// Image/audio token metadata attached to a non-text [`MtmdInputChunk`].
2020#[derive(Debug)]
2021pub struct MtmdImageTokens<'chunks> {
2022 ptr: *const sys::mtmd_image_tokens,
2023 _marker: std::marker::PhantomData<&'chunks MtmdInputChunks>,
2024}
2025
2026impl MtmdImageTokens<'_> {
2027 /// Total number of embedding tokens.
2028 #[must_use]
2029 pub fn n_tokens(&self) -> usize {
2030 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2031 // remaining arguments are scalars or pointers valid for the call.
2032 unsafe { sys::mtmd_image_tokens_get_n_tokens(self.ptr) }
2033 }
2034
2035 /// Width of the token grid.
2036 #[must_use]
2037 pub fn nx(&self) -> usize {
2038 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2039 // remaining arguments are scalars or pointers valid for the call.
2040 unsafe { sys::mtmd_image_tokens_get_nx(self.ptr) }
2041 }
2042
2043 /// Height of the token grid.
2044 #[must_use]
2045 pub fn ny(&self) -> usize {
2046 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2047 // remaining arguments are scalars or pointers valid for the call.
2048 unsafe { sys::mtmd_image_tokens_get_ny(self.ptr) }
2049 }
2050
2051 /// Number of temporal positions (M-RoPE variant; equals `n_tokens` otherwise).
2052 #[must_use]
2053 pub fn n_pos(&self) -> i32 {
2054 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2055 // remaining arguments are scalars or pointers valid for the call.
2056 unsafe { sys::mtmd_image_tokens_get_n_pos(self.ptr) }
2057 }
2058
2059 /// Optional ID for KV cache tracking.
2060 #[must_use]
2061 pub fn id(&self) -> Option<&str> {
2062 // SAFETY: a read through a live handle (or no handle at all, for the
2063 // library-wide accessors); the returned pointer is only converted
2064 // below, never freed here.
2065 let ptr = unsafe { sys::mtmd_image_tokens_get_id(self.ptr) };
2066 if ptr.is_null() {
2067 return None;
2068 }
2069 // SAFETY: the pointer comes from an mtmd accessor, which returns a static or
2070 // handle-owned NUL-terminated string that outlives the borrow taken here.
2071 unsafe { CStr::from_ptr(ptr) }.to_str().ok()
2072 }
2073
2074 /// Compute the per-token decoder positions used by M-RoPE models.
2075 ///
2076 /// Returns a vector of length [`n_tokens`](Self::n_tokens). Each entry
2077 /// is relative to `pos_0`; for non-M-RoPE models this typically reduces
2078 /// to `(0, i, 0, 0)` for the i-th token.
2079 ///
2080 /// Wraps `mtmd_helper_image_get_decoder_pos`.
2081 #[must_use]
2082 pub fn decoder_positions(&self, pos_0: i32) -> Vec<MtmdDecoderPos> {
2083 let n = self.n_tokens();
2084 let mut out = vec![MtmdDecoderPos::default(); n];
2085 if n == 0 {
2086 return out;
2087 }
2088 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2089 // remaining arguments are scalars or pointers valid for the call.
2090 unsafe {
2091 sys::mtmd_helper_image_get_decoder_pos(
2092 self.ptr,
2093 pos_0,
2094 out.as_mut_ptr().cast::<sys::mtmd_decoder_pos>(),
2095 );
2096 }
2097 out
2098 }
2099}
2100
2101// ─────────────────────────────────────────────────────────────────────────────
2102// LlamaContext extension
2103// ─────────────────────────────────────────────────────────────────────────────
2104
2105use crate::context::LlamaContext;
2106
2107impl LlamaContext<'_> {
2108 /// Expose the raw `llama_context` pointer for use with mtmd helpers.
2109 ///
2110 /// # Safety
2111 ///
2112 /// The pointer is valid for the lifetime of this `LlamaContext` and must
2113 /// not be freed by the caller.
2114 #[must_use]
2115 pub fn as_ptr(&self) -> *mut sys::llama_context {
2116 self.context.as_ptr()
2117 }
2118}
2119
2120#[cfg(test)]
2121mod tests {
2122 use super::*;
2123
2124 #[test]
2125 fn decoder_pos_layout_matches_sys() {
2126 // The Rust MtmdDecoderPos is cast to sys::mtmd_decoder_pos at the
2127 // FFI boundary in `MtmdImageTokens::decoder_positions`. Verify the
2128 // assumption.
2129 assert_eq!(
2130 std::mem::size_of::<MtmdDecoderPos>(),
2131 std::mem::size_of::<sys::mtmd_decoder_pos>(),
2132 );
2133 assert_eq!(
2134 std::mem::align_of::<MtmdDecoderPos>(),
2135 std::mem::align_of::<sys::mtmd_decoder_pos>(),
2136 );
2137 assert_eq!(std::mem::offset_of!(MtmdDecoderPos, t), 0);
2138 assert_eq!(std::mem::offset_of!(MtmdDecoderPos, x), 4);
2139 assert_eq!(std::mem::offset_of!(MtmdDecoderPos, y), 8);
2140 assert_eq!(std::mem::offset_of!(MtmdDecoderPos, z), 12);
2141 }
2142
2143 #[test]
2144 fn input_text_records_byte_length_and_nul_terminates() {
2145 let input = MtmdInputText::new("hello", true, false);
2146 // text_len is the prompt length, excluding the trailing NUL sentinel.
2147 assert_eq!(input.text_len, 5);
2148 assert_eq!(input.text, b"hello\0");
2149 assert!(input.add_special);
2150 assert!(!input.parse_special);
2151 }
2152
2153 /// The resampler takes no model and no context, so unlike the rest of
2154 /// mtmd it can be exercised directly.
2155 #[test]
2156 fn resampler_rejects_a_non_positive_rate() {
2157 assert!(matches!(
2158 MtmdResampler::new(0, 16_000),
2159 Err(MtmdError::ResamplerInitFailed {
2160 rate_in: 0,
2161 rate_out: 16_000
2162 })
2163 ));
2164 assert!(MtmdResampler::new(16_000, -1).is_err());
2165 }
2166
2167 /// Equal rates are upstream's passthrough path, where the block comes
2168 /// straight back out — identical samples, identical count.
2169 #[test]
2170 fn resampler_passes_equal_rates_through() {
2171 let mut resampler = MtmdResampler::new(16_000, 16_000).expect("init passthrough");
2172 let input = [0.0_f32, 0.25, -0.5, 1.0];
2173 assert_eq!(resampler.process(&input).expect("process"), &input);
2174 }
2175
2176 /// Halving the rate must halve the sample count, within the few samples
2177 /// the low-pass filter holds back to join the next block.
2178 #[test]
2179 fn resampler_halves_the_sample_count() {
2180 let mut resampler = MtmdResampler::new(32_000, 16_000).expect("init 32k -> 16k");
2181 let input: Vec<f32> = (0..512_i16).map(|i| (f32::from(i) / 512.0).sin()).collect();
2182 let n_out = resampler.process(&input).expect("process").len();
2183 assert!(
2184 (240..=256).contains(&n_out),
2185 "32k -> 16k on 512 samples produced {n_out}, expected about 256"
2186 );
2187 }
2188
2189 /// An empty block is legal and drains nothing — a realtime caller polling
2190 /// an idle input hits this on every tick.
2191 #[test]
2192 fn resampler_accepts_an_empty_block() {
2193 let mut resampler = MtmdResampler::new(44_100, 16_000).expect("init 44.1k -> 16k");
2194 assert!(resampler.process(&[]).expect("process").is_empty());
2195 }
2196
2197 #[test]
2198 fn input_text_preserves_interior_nul() {
2199 // The whole point of upstream's `text_len`: a prompt with an embedded
2200 // NUL must keep its full length rather than truncating at the NUL.
2201 let input = MtmdInputText::from_bytes(b"a\0b", false, true);
2202 assert_eq!(input.text_len, 3);
2203 assert_eq!(input.text, b"a\0b\0");
2204 }
2205
2206 /// Restoring a chunk from garbage must return an error, not abort. The
2207 /// underlying C returns null on failure, and a null deref here would take
2208 /// the process with it.
2209 /// Probing a file that is not an mmproj must report "no modalities"
2210 /// rather than crash — a server calls this on a user-supplied path.
2211 #[test]
2212 fn mmproj_caps_on_a_non_mmproj_file_reports_nothing() {
2213 let caps = mmproj_caps("/definitely/not/a/model.gguf").expect("no NUL in path");
2214 assert!(!caps.vision);
2215 assert!(!caps.audio);
2216 }
2217
2218 #[test]
2219 fn mmproj_caps_rejects_interior_nul() {
2220 assert!(mmproj_caps("a\0b").is_err());
2221 }
2222
2223 #[test]
2224 fn load_chunk_rejects_garbage() {
2225 let err = MtmdInputChunks::load_chunk(b"not a serialized chunk").unwrap_err();
2226 assert!(matches!(err, MtmdError::ChunkLoadFailed), "got {err:?}");
2227 }
2228
2229 #[test]
2230 fn load_chunk_rejects_empty_input() {
2231 assert!(MtmdInputChunks::load_chunk(&[]).is_err());
2232 }
2233
2234 /// A truncated buffer is the realistic corruption case for a chunk read
2235 /// back off disk beside a session file.
2236 #[test]
2237 fn load_chunk_rejects_truncated_input() {
2238 assert!(MtmdInputChunks::load_chunk(&[0u8; 4]).is_err());
2239 }
2240
2241 #[test]
2242 fn input_text_try_new_is_infallible() {
2243 let input = MtmdInputText::try_new("marker \u{1} data", true, true)
2244 .expect("try_new no longer rejects any input");
2245 assert_eq!(input.text_len, "marker \u{1} data".len());
2246 }
2247}
2248
2249// ─────────────────────────────────────────────────────────────────────────────
2250// OwnedMtmdInputChunk
2251// ─────────────────────────────────────────────────────────────────────────────
2252
2253/// A chunk that owns its allocation, as returned by
2254/// [`MtmdInputChunks::load_chunk`] or [`MtmdInputChunk::to_placeholder`].
2255///
2256/// [`MtmdInputChunk`] borrows from the [`MtmdInputChunks`] list that holds it;
2257/// this one stands alone and frees itself on drop.
2258pub struct OwnedMtmdInputChunk {
2259 ptr: NonNull<sys::mtmd_input_chunk>,
2260}
2261
2262impl std::fmt::Debug for OwnedMtmdInputChunk {
2263 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2264 f.debug_struct("OwnedMtmdInputChunk")
2265 .field("chunk_type", &self.chunk_type())
2266 .field("n_tokens", &self.n_tokens())
2267 .finish()
2268 }
2269}
2270
2271impl Drop for OwnedMtmdInputChunk {
2272 fn drop(&mut self) {
2273 // SAFETY: this runs once from `Drop`, the handle is non-null, and nothing
2274 // reads it afterwards.
2275 unsafe { sys::mtmd_input_chunk_free(self.ptr.as_ptr()) }
2276 }
2277}
2278
2279impl OwnedMtmdInputChunk {
2280 /// The type of this chunk.
2281 #[must_use]
2282 pub fn chunk_type(&self) -> MtmdInputChunkType {
2283 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2284 // remaining arguments are scalars or pointers valid for the call.
2285 MtmdInputChunkType::from(unsafe { sys::mtmd_input_chunk_get_type(self.ptr.as_ptr()) })
2286 }
2287
2288 /// Total number of tokens in this chunk.
2289 #[must_use]
2290 pub fn n_tokens(&self) -> usize {
2291 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2292 // remaining arguments are scalars or pointers valid for the call.
2293 unsafe { sys::mtmd_input_chunk_get_n_tokens(self.ptr.as_ptr()) }
2294 }
2295
2296 /// Number of temporal positions.
2297 #[must_use]
2298 pub fn n_pos(&self) -> i32 {
2299 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2300 // remaining arguments are scalars or pointers valid for the call.
2301 unsafe { sys::mtmd_input_chunk_get_n_pos(self.ptr.as_ptr()) }
2302 }
2303
2304 /// Serialize this chunk's metadata, as [`MtmdInputChunk::save`] does.
2305 ///
2306 /// # Errors
2307 ///
2308 /// Returns [`MtmdError::ChunkSaveFailed`] if llama.cpp cannot serialize it.
2309 pub fn save(&self) -> Result<Vec<u8>> {
2310 let mut needed: usize = 0;
2311 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2312 // remaining arguments are scalars or pointers valid for the call.
2313 let rc = unsafe {
2314 sys::mtmd_input_chunk_save(self.ptr.as_ptr(), std::ptr::null_mut(), 0, &raw mut needed)
2315 };
2316 if rc != 0 && needed == 0 {
2317 return Err(MtmdError::ChunkSaveFailed(rc));
2318 }
2319 let mut buf = vec![0u8; needed];
2320 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2321 // remaining arguments are scalars or pointers valid for the call.
2322 let rc = unsafe {
2323 sys::mtmd_input_chunk_save(
2324 self.ptr.as_ptr(),
2325 buf.as_mut_ptr().cast::<std::os::raw::c_char>(),
2326 buf.len(),
2327 &raw mut needed,
2328 )
2329 };
2330 if rc != 0 {
2331 return Err(MtmdError::ChunkSaveFailed(rc));
2332 }
2333 buf.truncate(needed);
2334 Ok(buf)
2335 }
2336}
2337
2338// ─────────────────────────────────────────────────────────────────────────────
2339// MtmdBatch
2340// ─────────────────────────────────────────────────────────────────────────────
2341
2342/// Encode several media chunks in one pass.
2343///
2344/// [`MtmdContext::encode_chunk`] handles one chunk at a time; this batches
2345/// them, which is what you want for a multi-image prompt or a run of video
2346/// frames — the vision encoder runs once over the whole set instead of once per
2347/// image.
2348///
2349/// A batch belongs to the context that created it and borrows it for its
2350/// lifetime. Chunks are *not* owned by the batch, so they must outlive it too.
2351///
2352/// Wraps `mtmd_batch_init` / `mtmd_batch_add_chunk` / `mtmd_batch_encode`.
2353pub struct MtmdBatch<'ctx> {
2354 ptr: NonNull<sys::mtmd_batch>,
2355 _ctx: std::marker::PhantomData<&'ctx MtmdContext>,
2356}
2357
2358impl std::fmt::Debug for MtmdBatch<'_> {
2359 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2360 f.debug_struct("MtmdBatch").finish_non_exhaustive()
2361 }
2362}
2363
2364impl Drop for MtmdBatch<'_> {
2365 fn drop(&mut self) {
2366 // SAFETY: this runs once from `Drop`, the handle is non-null, and nothing
2367 // reads it afterwards.
2368 unsafe { sys::mtmd_batch_free(self.ptr.as_ptr()) }
2369 }
2370}
2371
2372impl<'ctx> MtmdBatch<'ctx> {
2373 /// Start a batch against `ctx`.
2374 ///
2375 /// # Errors
2376 ///
2377 /// Returns [`MtmdError::BatchCreateFailed`] if llama.cpp returns null.
2378 pub fn new(ctx: &'ctx MtmdContext) -> Result<Self> {
2379 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
2380 // and the model/context handles are borrowed — and the result is checked
2381 // for null before being wrapped.
2382 let ptr = unsafe { sys::mtmd_batch_init(ctx.ptr.as_ptr()) };
2383 NonNull::new(ptr)
2384 .map(|ptr| Self {
2385 ptr,
2386 _ctx: std::marker::PhantomData,
2387 })
2388 .ok_or(MtmdError::BatchCreateFailed)
2389 }
2390
2391 /// Add a media chunk. Text chunks are rejected.
2392 ///
2393 /// # Errors
2394 ///
2395 /// Returns [`MtmdError::BatchAddFailed`] — code `2` means the batch is
2396 /// full and the chunk was not added (start a new batch), code `3` means it
2397 /// cannot be batched with what is already there (differing image
2398 /// geometry, say).
2399 pub fn add_chunk(&mut self, chunk: &MtmdInputChunk<'_>) -> Result<()> {
2400 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2401 // remaining arguments are scalars or pointers valid for the call.
2402 let rc = unsafe { sys::mtmd_batch_add_chunk(self.ptr.as_ptr(), chunk.ptr) };
2403 if rc == 0 {
2404 Ok(())
2405 } else {
2406 Err(MtmdError::BatchAddFailed(rc))
2407 }
2408 }
2409
2410 /// Encode every chunk added so far.
2411 ///
2412 /// # Errors
2413 ///
2414 /// Returns [`MtmdError::EncodeError`] on failure.
2415 pub fn encode(&mut self) -> Result<()> {
2416 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2417 // remaining arguments are scalars or pointers valid for the call.
2418 let rc = unsafe { sys::mtmd_batch_encode(self.ptr.as_ptr()) };
2419 if rc == 0 {
2420 Ok(())
2421 } else {
2422 Err(MtmdError::EncodeError(rc))
2423 }
2424 }
2425
2426 /// Borrow the embeddings produced for `chunk` by the last [`Self::encode`].
2427 ///
2428 /// Returns `None` if the chunk was not part of this batch or encoding has
2429 /// not run. The slice is owned by the batch and is invalidated by the next
2430 /// `encode`.
2431 ///
2432 /// # Safety of the returned length
2433 ///
2434 /// llama.cpp reports only a pointer, so the length is derived from the
2435 /// chunk's token count and the context's embedding dimension.
2436 #[must_use]
2437 pub fn output_embd(&self, model: &LlamaModel, chunk: &MtmdInputChunk<'_>) -> Option<&[f32]> {
2438 // The width is `n_embd_inp`, and `chunk` is the key the buffer is
2439 // looked up by — so deriving the length from that same chunk cannot
2440 // disagree with the buffer it describes. Taking a bare `usize` here
2441 // let a caller name any length at all.
2442 let n_embd_inp = usize::try_from(model.n_embd_inp()).ok()?;
2443 let len = chunk.n_tokens().checked_mul(n_embd_inp)?;
2444 if len == 0 {
2445 return Some(&[]);
2446 }
2447 // SAFETY: `mtmd_batch_get_output_embd` returns either null or the
2448 // buffer it holds for exactly this chunk, and `len` is that chunk's
2449 // token count times the input embedding width — upstream's own
2450 // documented size. The borrow is tied to `&self`.
2451 unsafe {
2452 let ptr = sys::mtmd_batch_get_output_embd(self.ptr.as_ptr(), chunk.ptr);
2453 if ptr.is_null() {
2454 return None;
2455 }
2456 Some(slice::from_raw_parts(ptr, len))
2457 }
2458 }
2459}
2460
2461// ─────────────────────────────────────────────────────────────────────────────
2462// Audio generation
2463// ─────────────────────────────────────────────────────────────────────────────
2464
2465/// Container for generated audio.
2466#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2467pub enum MtmdAudioOutType {
2468 /// Raw PCM samples.
2469 Pcm,
2470 /// A complete WAV file: PCM 16-bit little-endian, mono.
2471 Wav,
2472}
2473
2474impl MtmdAudioOutType {
2475 fn as_raw(self) -> sys::mtmd_helper_gen_audio_outtype {
2476 match self {
2477 Self::Pcm => sys::MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM,
2478 Self::Wav => sys::MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV,
2479 }
2480 }
2481}
2482
2483/// What to synthesize, and how.
2484#[derive(Debug, Clone)]
2485pub struct MtmdAudioRequest {
2486 /// Sequence id to generate under.
2487 pub seq_id: i32,
2488 /// Text to speak.
2489 pub prompt: String,
2490 /// BCP-47-ish language hint, if the pipeline takes one.
2491 pub lang: Option<String>,
2492 /// Top-k for the backbone sampler.
2493 pub top_k: i32,
2494 /// Top-p for the backbone sampler.
2495 pub top_p: f32,
2496 /// Seed; `u32::MAX` means random.
2497 pub seed: u32,
2498 /// Container for [`MtmdAudioGen::output`].
2499 pub out_type: MtmdAudioOutType,
2500}
2501
2502impl MtmdAudioRequest {
2503 /// A request to speak `prompt` with upstream's defaults.
2504 #[must_use]
2505 pub fn new(prompt: impl Into<String>) -> Self {
2506 Self {
2507 seq_id: 0,
2508 prompt: prompt.into(),
2509 lang: None,
2510 top_k: 40,
2511 top_p: 0.9,
2512 seed: u32::MAX,
2513 out_type: MtmdAudioOutType::Wav,
2514 }
2515 }
2516}
2517
2518/// Text-to-speech through an mmproj audio-generation pipeline.
2519///
2520/// This is the *other* direction of multimodal: where [`MtmdBitmap`] feeds
2521/// audio in, this drives a pipeline that emits it. The loop is explicitly
2522/// stateless on llama.cpp's side, so it runs in two phases:
2523///
2524/// 1. [`Self::set_input`], then [`Self::step_prompt`] until it returns `0` —
2525/// the prompt is consumed `n_batch` tokens at a time.
2526/// 2. [`Self::step_gen`] per frame until it reports stop.
2527/// 3. [`Self::output`] for the finished audio.
2528///
2529/// Wraps `mtmd_helper_gen_audio_*`.
2530pub struct MtmdAudioGen<'ctx> {
2531 ptr: NonNull<sys::mtmd_helper_gen_audio>,
2532 _ctx: std::marker::PhantomData<&'ctx MtmdContext>,
2533}
2534
2535impl std::fmt::Debug for MtmdAudioGen<'_> {
2536 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2537 f.debug_struct("MtmdAudioGen").finish_non_exhaustive()
2538 }
2539}
2540
2541impl Drop for MtmdAudioGen<'_> {
2542 fn drop(&mut self) {
2543 // SAFETY: this runs once from `Drop`, the handle is non-null, and nothing
2544 // reads it afterwards.
2545 unsafe { sys::mtmd_helper_gen_audio_free(self.ptr.as_ptr()) }
2546 }
2547}
2548
2549impl<'ctx> MtmdAudioGen<'ctx> {
2550 /// Attach a generator to a llama context and an mtmd context.
2551 ///
2552 /// # Errors
2553 ///
2554 /// Returns [`MtmdError::ContextCreateFailed`] if the mmproj has no
2555 /// audio-generation pipeline.
2556 pub fn new(
2557 lctx: &mut crate::context::LlamaContext<'_>,
2558 mctx: &'ctx MtmdContext,
2559 ) -> Result<Self> {
2560 let ptr =
2561 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
2562 // and the model/context handles are borrowed — and the result is checked
2563 // for null before being wrapped.
2564 unsafe { sys::mtmd_helper_gen_audio_init(lctx.context.as_ptr(), mctx.ptr.as_ptr()) };
2565 NonNull::new(ptr)
2566 .map(|ptr| Self {
2567 ptr,
2568 _ctx: std::marker::PhantomData,
2569 })
2570 .ok_or(MtmdError::ContextCreateFailed)
2571 }
2572
2573 /// Clear all state, ready for another utterance.
2574 pub fn reset(&mut self) {
2575 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2576 // remaining arguments are scalars or pointers valid for the call.
2577 unsafe { sys::mtmd_helper_gen_audio_reset(self.ptr.as_ptr()) }
2578 }
2579
2580 /// Set what to synthesize. `speaker_ref` is an optional voice reference for
2581 /// pipelines that support cloning.
2582 ///
2583 /// # Errors
2584 ///
2585 /// Returns [`MtmdError::EvalError`] if llama.cpp rejects the request, or
2586 /// [`MtmdError::InvalidPath`] if a string contains an interior NUL.
2587 pub fn set_input(
2588 &mut self,
2589 request: &MtmdAudioRequest,
2590 speaker_ref: Option<&MtmdBitmap>,
2591 ) -> Result<()> {
2592 let prompt = CString::new(request.prompt.as_str())?;
2593 let lang = request.lang.as_deref().map(CString::new).transpose()?;
2594 // Start from upstream's defaults and override, rather than naming every
2595 // field: a struct literal here breaks on every field llama.cpp adds,
2596 // which is how `stream` broke the b11829 bump. The same reason
2597 // `LlamaContextParams` is seeded from `llama_context_default_params`.
2598 //
2599 // SAFETY: `mtmd_helper_gen_audio_inp_default` takes no arguments and
2600 // returns a by-value POD struct.
2601 let mut inp = unsafe { sys::mtmd_helper_gen_audio_inp_default() };
2602 inp.seq_id = request.seq_id;
2603 inp.prompt = prompt.as_ptr();
2604 inp.prompt_len = request.prompt.len();
2605 inp.speaker_ref = speaker_ref.map_or(std::ptr::null_mut(), |b| b.ptr.as_ptr());
2606 inp.lang = lang.as_ref().map_or(std::ptr::null(), |c| c.as_ptr());
2607 inp.top_k = request.top_k;
2608 inp.top_p = request.top_p;
2609 inp.seed = request.seed;
2610 inp.out_type = request.out_type.as_raw();
2611 // `stream` (new in b11829) requires `output()` after every `step_gen`.
2612 // [`MtmdAudioGen`] collects the whole clip and reads it once, so leave
2613 // it off regardless of what upstream defaults it to.
2614 inp.stream = false;
2615 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2616 // remaining arguments are scalars or pointers valid for the call.
2617 let rc = unsafe { sys::mtmd_helper_gen_audio_set_input(self.ptr.as_ptr(), &raw const inp) };
2618 if rc == 0 {
2619 Ok(())
2620 } else {
2621 Err(MtmdError::EvalError(rc))
2622 }
2623 }
2624
2625 /// Consume up to `n_batch` prompt tokens.
2626 ///
2627 /// Returns the number of prompt tokens still outstanding; call again until
2628 /// it returns `0`, then move on to [`Self::step_gen`].
2629 ///
2630 /// # Errors
2631 ///
2632 /// Returns [`MtmdError::EvalError`] if llama.cpp reports a negative code.
2633 pub fn step_prompt(&mut self, n_batch: i32) -> Result<i32> {
2634 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2635 // remaining arguments are scalars or pointers valid for the call.
2636 let rc = unsafe { sys::mtmd_helper_gen_audio_step_prompt(self.ptr.as_ptr(), n_batch) };
2637 if rc < 0 {
2638 return Err(MtmdError::EvalError(rc));
2639 }
2640 Ok(rc)
2641 }
2642
2643 /// Whether the next [`step_gen`](Self::step_gen) wants a *text* token.
2644 ///
2645 /// Interleaved pipelines alternate: when this is `true` the caller samples
2646 /// a token from the logits and passes it as `sampled`; when `false` the
2647 /// next step produces an audio frame from `h_state_in` instead. Getting
2648 /// this backwards feeds a stale token into a frame step, so check it each
2649 /// iteration rather than assuming the pattern.
2650 ///
2651 /// Wraps `mtmd_helper_gen_audio_next_is_text`, new in `b12032`.
2652 #[must_use]
2653 pub fn next_is_text(&mut self) -> bool {
2654 // SAFETY: a live `&mut self` gives an exclusive, non-null generator.
2655 unsafe { sys::mtmd_helper_gen_audio_next_is_text(self.ptr.as_ptr()) }
2656 }
2657
2658 /// Logit bias to apply before sampling the next text token.
2659 ///
2660 /// This is how the model keeps a text-only response from switching to
2661 /// audio mid-sentence, so sampling without it can produce a token the
2662 /// pipeline cannot act on. Feed it to
2663 /// [`LlamaSampler::logit_bias`](crate::sampling::LlamaSampler::logit_bias).
2664 ///
2665 /// Empty when the pipeline has no bias for this step. Wraps
2666 /// `mtmd_helper_gen_audio_get_logit_bias`, new in `b12032`.
2667 #[must_use]
2668 pub fn logit_bias(&mut self) -> Vec<llama_cpp_sys_4::llama_logit_bias> {
2669 let mut n_bias: usize = 0;
2670 // SAFETY: exclusive non-null generator; upstream writes the count
2671 // through `n_bias` and returns a pointer owned by the generator that
2672 // stays valid until the next step. Copying out here means the returned
2673 // Vec does not alias it.
2674 unsafe {
2675 let ptr = sys::mtmd_helper_gen_audio_get_logit_bias(self.ptr.as_ptr(), &raw mut n_bias);
2676 if ptr.is_null() || n_bias == 0 {
2677 return Vec::new();
2678 }
2679 std::slice::from_raw_parts(ptr, n_bias).to_vec()
2680 }
2681 }
2682
2683 /// Generate one audio frame.
2684 ///
2685 /// `sampled` is the backbone token just sampled, or `None` for pipelines
2686 /// with no discrete backbone token. `h_state_in` is the hidden state fed
2687 /// back from the previous step.
2688 ///
2689 /// Returns `(hidden_state, stop)`. `stop` marks end-of-speech: the caller
2690 /// must break the loop. The hidden state borrows generator memory that the
2691 /// next `step_gen` or [`Self::reset`] invalidates, hence the `&mut self`
2692 /// borrow being released before you can call again.
2693 ///
2694 /// # Errors
2695 ///
2696 /// Returns [`MtmdError::EvalError`] on a negative code.
2697 pub fn step_gen(
2698 &mut self,
2699 sampled: Option<crate::token::LlamaToken>,
2700 h_state_in: Option<&[f32]>,
2701 model: &LlamaModel,
2702 ) -> Result<(Option<Vec<f32>>, bool)> {
2703 let token = sampled.map_or(sys::LLAMA_TOKEN_NULL, |t| t.0);
2704 let in_ptr = h_state_in.map_or(std::ptr::null(), <[f32]>::as_ptr);
2705 let mut out_ptr: *const f32 = std::ptr::null();
2706 let mut stop = false;
2707 // SAFETY: a live `&mut self` gives an exclusive, non-null generator.
2708 // `in_ptr` is either null or borrowed from `h_state_in` for the call,
2709 // and the two out-params are stack locals upstream writes through.
2710 let rc = unsafe {
2711 sys::mtmd_helper_gen_audio_step_gen(
2712 self.ptr.as_ptr(),
2713 token,
2714 in_ptr,
2715 &raw mut out_ptr,
2716 &raw mut stop,
2717 )
2718 };
2719 if rc < 0 {
2720 return Err(MtmdError::EvalError(rc));
2721 }
2722 // The hidden state is one row of `n_embd` floats — upstream builds it
2723 // with `h_state_buf.assign(he, he + n_embd)` where `n_embd` is
2724 // `llama_model_n_embd(model)`. Taking that from the model rather than
2725 // from the caller is what keeps this a safe function.
2726 let n_embd = usize::try_from(model.n_embd()).unwrap_or(0);
2727 // Copy rather than borrow: upstream documents the buffer as valid only
2728 // until the next step_gen/reset, which a returned slice could outlive.
2729 let state = if out_ptr.is_null() || n_embd == 0 {
2730 None
2731 } else {
2732 // SAFETY: `out_ptr` is non-null and points at the generator's
2733 // hidden-state buffer, which upstream sized at `n_embd` floats.
2734 // The copy happens before any call that could invalidate it.
2735 Some(unsafe { slice::from_raw_parts(out_ptr, n_embd) }.to_vec())
2736 };
2737 Ok((state, stop))
2738 }
2739
2740 /// Collect the generated audio.
2741 ///
2742 /// Returns `(sample_rate, bytes, n_samples)`. `bytes` is raw PCM or a
2743 /// complete WAV file depending on the request's
2744 /// [`MtmdAudioOutType`].
2745 ///
2746 /// # Errors
2747 ///
2748 /// Returns [`MtmdError::EvalError`] if nothing has been generated.
2749 pub fn output(&mut self) -> Result<(i32, Vec<u8>, i64)> {
2750 let mut sample_rate: i32 = 0;
2751 let mut data: *const std::os::raw::c_char = std::ptr::null();
2752 let mut data_len: usize = 0;
2753 let mut n_samples: i64 = 0;
2754 // SAFETY: `self.ptr` is a live, non-null handle kept alive by this borrow, and the
2755 // remaining arguments are scalars or pointers valid for the call.
2756 let rc = unsafe {
2757 sys::mtmd_helper_gen_audio_get_output(
2758 self.ptr.as_ptr(),
2759 &raw mut sample_rate,
2760 &raw mut data,
2761 &raw mut data_len,
2762 &raw mut n_samples,
2763 )
2764 };
2765 if rc != 0 {
2766 return Err(MtmdError::EvalError(rc));
2767 }
2768 let bytes = if data.is_null() || data_len == 0 {
2769 Vec::new()
2770 } else {
2771 // Copied for the same reason as step_gen: valid only until the next
2772 // get_output/reset.
2773 // SAFETY: `data` and `data_len` are the pointer and byte count upstream wrote
2774 // through its out-params for this generator's audio buffer.
2775 unsafe { slice::from_raw_parts(data.cast::<u8>(), data_len) }.to_vec()
2776 };
2777 Ok((sample_rate, bytes, n_samples))
2778 }
2779}
2780
2781// ─────────────────────────────────────────────────────────────────────────────
2782// Explicit input parts
2783// ─────────────────────────────────────────────────────────────────────────────
2784
2785/// One element of a marker-free prompt, for
2786/// [`MtmdContext::tokenize_from_parts`].
2787///
2788/// Borrows rather than owns, so the caller keeps control of bitmap lifetimes —
2789/// a bitmap is usually reused across several prompts.
2790#[derive(Debug)]
2791pub enum MtmdInputPart<'a> {
2792 /// A run of text, with its own `parse_special` setting.
2793 Text(&'a MtmdInputText<'a>),
2794 /// An image or audio bitmap spliced in at this position.
2795 Bitmap(&'a MtmdBitmap),
2796}
2797
2798// ─────────────────────────────────────────────────────────────────────────────
2799// Audio-generation capabilities
2800// ─────────────────────────────────────────────────────────────────────────────
2801
2802/// Which audio-generation pipeline an mmproj implements.
2803#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2804pub enum MtmdGenAudioType {
2805 /// Qwen3-TTS.
2806 Qwen3Tts,
2807 /// `PocketTTS`.
2808 PocketTts,
2809 /// A pipeline this crate does not know, added upstream since this release.
2810 Unknown,
2811}
2812
2813impl MtmdGenAudioType {
2814 fn from_raw(raw: sys::mtmd_gen_audio_type) -> Self {
2815 match raw {
2816 sys::MTMD_GEN_AUDIO_TYPE_QWEN3TTS => Self::Qwen3Tts,
2817 sys::MTMD_GEN_AUDIO_TYPE_POCKETTTS => Self::PocketTts,
2818 _ => Self::Unknown,
2819 }
2820 }
2821}
2822
2823/// What a model and projector pair can take in and produce.
2824///
2825/// From `mtmd_helper_get_capabilities`. The three input flags answer "what can
2826/// I feed this?"; the three output flags answer "what will it give me back?" —
2827/// a text-to-speech model, for example, reports `text_gen: false` and
2828/// `audio_gen: true`, which no earlier predicate could express.
2829// A faithful 1:1 mirror of upstream's `mtmd_helper_cap`, which is eight bools.
2830// The lint's usual remedy — collapse them into an enum or bitflags — would put
2831// a translation layer between this and the C struct, making it harder to check
2832// that the fields still line up after a bump. Upstream's shape is the contract.
2833#[allow(clippy::struct_excessive_bools)]
2834#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2835pub struct MtmdCapabilities {
2836 /// Usable for chat. `false` for tts-only models (no chat template) and for
2837 /// realtime transcription models.
2838 pub chat: bool,
2839
2840 /// Accepts image input.
2841 pub vision: bool,
2842 /// Accepts audio input.
2843 pub audio: bool,
2844 /// Accepts video input. Also depends on the `MTMD_VIDEO` build option, and
2845 /// on `ffmpeg`/`ffprobe` at runtime — see [`MtmdVideo`].
2846 pub video: bool,
2847
2848 /// Supports realtime transcription through llama.cpp's
2849 /// `mtmd_audio_stream_*` API, which this crate does not wrap yet — reach
2850 /// for `llama-cpp-sys-4` directly if you need it.
2851 pub audio_stream: bool,
2852
2853 /// Generates text. `false` for an audio-only model.
2854 pub text_gen: bool,
2855 /// Generates audio.
2856 pub audio_gen: bool,
2857 /// Accepts a speaker reference clip for voice cloning.
2858 pub audio_gen_spk_ref: bool,
2859}
2860
2861/// What [`MtmdContext::gen_audio_info`] reports about a speech pipeline.
2862#[derive(Debug, Clone, PartialEq, Eq)]
2863pub struct MtmdGenAudioInfo {
2864 /// The pipeline implemented by this projector.
2865 pub pipeline: MtmdGenAudioType,
2866 /// Output sample rate in Hz, e.g. 24000 for Qwen3-TTS. Needed to write a
2867 /// correct WAV header or resample.
2868 pub sample_rate: i32,
2869 /// Weight-variant name, when the pipeline has variants.
2870 pub model_variant: Option<String>,
2871}
2872
2873// ─────────────────────────────────────────────────────────────────────────────
2874// Projector capability probe
2875// ─────────────────────────────────────────────────────────────────────────────
2876
2877/// Which modalities an mmproj file accepts.
2878#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2879pub struct MtmdCaps {
2880 /// Accepts image input.
2881 pub vision: bool,
2882 /// Accepts audio input.
2883 pub audio: bool,
2884}
2885
2886/// Read an mmproj file's input capabilities without loading it.
2887///
2888/// [`MtmdContext::init_from_file`] builds the full projector — weights, compute
2889/// buffers, the lot. This only reads enough metadata to answer "does this
2890/// accept images, audio, or both", which is what a server needs at startup to
2891/// decide whether a request is even servable.
2892///
2893/// Wraps `mtmd_get_cap_from_file`. Returns both flags `false` for a file that
2894/// is not a readable mmproj.
2895///
2896/// # Errors
2897///
2898/// Returns [`MtmdError::InvalidPath`] if the path contains an interior NUL, or
2899/// [`MtmdError::PathNotUtf8`] if it is not UTF-8.
2900pub fn mmproj_caps(path: impl AsRef<Path>) -> Result<MtmdCaps> {
2901 let path = path.as_ref().to_str().ok_or(MtmdError::PathNotUtf8)?;
2902 let c_path = CString::new(path)?;
2903 // SAFETY: the path is a `CString` alive for the call; upstream only reads the
2904 // file and returns a plain struct.
2905 let caps = unsafe { sys::mtmd_get_cap_from_file(c_path.as_ptr()) };
2906 Ok(MtmdCaps {
2907 vision: caps.inp_vision,
2908 audio: caps.inp_audio,
2909 })
2910}
2911
2912// ─────────────────────────────────────────────────────────────────────────────
2913// Lazy bitmaps
2914// ─────────────────────────────────────────────────────────────────────────────
2915
2916/// What a lazy-bitmap callback yields for one chunk index.
2917#[derive(Debug)]
2918pub enum MtmdLazyChunk {
2919 /// An image or audio bitmap. Ownership passes to llama.cpp.
2920 Bitmap(MtmdBitmap),
2921 /// A run of text to splice in at this position.
2922 Text(String),
2923 /// No more chunks; the placeholder removes itself from the prompt.
2924 End,
2925}
2926
2927/// A bitmap whose contents are produced on demand, during tokenization.
2928///
2929/// An ordinary [`MtmdBitmap`] holds decoded pixels or samples from the moment
2930/// it is built. This holds a callback instead, invoked with `0, 1, 2, …` while
2931/// the prompt is tokenized and expanding into however many chunks it yields.
2932/// That matters for two cases:
2933///
2934/// - a long video, where materialising every frame up front would not fit in
2935/// memory;
2936/// - media that may never be reached, because a stop sequence or a token
2937/// budget cuts the prompt short first.
2938///
2939/// The callback must outlive tokenization, so this owns it alongside the
2940/// bitmap and drops them in that order.
2941///
2942/// Wraps `mtmd_bitmap_init_lazy`.
2943pub struct MtmdLazyBitmap {
2944 // Declaration order is the drop order, and it matters: llama.cpp may touch
2945 // `user_data` while freeing the bitmap, so the bitmap must go first.
2946 bitmap: MtmdBitmap,
2947 _callback: Box<LazyCallbackState>,
2948}
2949
2950impl std::fmt::Debug for MtmdLazyBitmap {
2951 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2952 f.debug_struct("MtmdLazyBitmap").finish_non_exhaustive()
2953 }
2954}
2955
2956/// Heap home for the user closure, pointed at by `user_data`.
2957struct LazyCallbackState {
2958 func: Box<dyn FnMut(usize) -> MtmdLazyChunk>,
2959}
2960
2961impl MtmdLazyBitmap {
2962 /// Build a lazy bitmap identified by `id` (conventionally a file hash).
2963 ///
2964 /// `callback` is called with increasing chunk indices until it returns
2965 /// [`MtmdLazyChunk::End`].
2966 ///
2967 /// # Errors
2968 ///
2969 /// Returns [`MtmdError::BitmapCreateFailed`] if llama.cpp returns null, or
2970 /// [`MtmdError::InvalidPath`] if `id` contains an interior NUL.
2971 pub fn new<F>(ctx: &MtmdContext, id: &str, callback: F) -> Result<Self>
2972 where
2973 F: FnMut(usize) -> MtmdLazyChunk + 'static,
2974 {
2975 let c_id = CString::new(id)?;
2976 let mut state = Box::new(LazyCallbackState {
2977 func: Box::new(callback),
2978 });
2979 let user_data = std::ptr::from_mut(state.as_mut()).cast::<std::os::raw::c_void>();
2980
2981 // SAFETY: every pointer argument is alive for the call — the paths are `CString`s
2982 // and the model/context handles are borrowed — and the result is checked
2983 // for null before being wrapped.
2984 let ptr = unsafe {
2985 sys::mtmd_bitmap_init_lazy(
2986 ctx.ptr.as_ptr(),
2987 c_id.as_ptr(),
2988 user_data,
2989 Some(lazy_trampoline),
2990 )
2991 };
2992 let bitmap = MtmdBitmap {
2993 ptr: NonNull::new(ptr).ok_or(MtmdError::BitmapCreateFailed)?,
2994 };
2995 Ok(Self {
2996 bitmap,
2997 _callback: state,
2998 })
2999 }
3000
3001 /// Borrow this as an ordinary bitmap, for passing to
3002 /// [`MtmdContext::tokenize`].
3003 #[must_use]
3004 pub fn as_bitmap(&self) -> &MtmdBitmap {
3005 &self.bitmap
3006 }
3007}
3008
3009/// C entry point for [`MtmdLazyBitmap`].
3010///
3011/// Returns `0` when a chunk was produced, `-1` at EOF, `-2` on error. A Rust
3012/// panic must not unwind into C, so it is caught and reported as `-2`.
3013extern "C" fn lazy_trampoline(
3014 chunk_idx: usize,
3015 user_data: *mut std::os::raw::c_void,
3016 out_bitmap: *mut *mut sys::mtmd_bitmap,
3017 out_text: *mut *mut std::os::raw::c_char,
3018) -> std::os::raw::c_int {
3019 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3020 if user_data.is_null() {
3021 return -2;
3022 }
3023 // SAFETY: `user_data` is the pointer this crate handed to llama.cpp
3024 // when registering the callback, checked non-null just above. It
3025 // points at a `LazyCallbackState` that outlives the tokenize call,
3026 // and llama.cpp invokes the callback from one thread at a time, so
3027 // the exclusive reference is not aliased.
3028 let state = unsafe { &mut *user_data.cast::<LazyCallbackState>() };
3029 match (state.func)(chunk_idx) {
3030 MtmdLazyChunk::Bitmap(bitmap) => {
3031 // Ownership moves to llama.cpp, which frees it with
3032 // `mtmd_bitmap_free`; skip our own Drop.
3033 let raw = bitmap.ptr.as_ptr();
3034 std::mem::forget(bitmap);
3035 // SAFETY: `out_bitmap` is an out-param llama.cpp provided for this callback,
3036 // and `raw` is a bitmap whose ownership has just been released with
3037 // `mem::forget`, so llama.cpp is now responsible for freeing it.
3038 unsafe { *out_bitmap = raw };
3039 0
3040 }
3041 MtmdLazyChunk::Text(text) => {
3042 let Ok(c_text) = CString::new(text) else {
3043 return -2;
3044 };
3045 // llama.cpp releases this with `free()`, so it must come from
3046 // malloc — a Rust-allocated buffer would be freed by the wrong
3047 // allocator.
3048 // SAFETY: `c_text` is alive for the call, and `strdup` is used because
3049 // llama.cpp releases this string with `free()` — a Rust-allocated buffer
3050 // would be handed to the wrong allocator.
3051 let dup = unsafe { strdup(c_text.as_ptr()) };
3052 if dup.is_null() {
3053 return -2;
3054 }
3055 // SAFETY: `out_text` is an out-param llama.cpp provided, and `dup` is a
3056 // non-null malloc'd string (checked above) that llama.cpp now owns.
3057 unsafe { *out_text = dup };
3058 0
3059 }
3060 MtmdLazyChunk::End => -1,
3061 }
3062 }));
3063 result.unwrap_or(-2)
3064}
3065
3066// ─────────────────────────────────────────────────────────────────────────────
3067// Audio resampling
3068// ─────────────────────────────────────────────────────────────────────────────
3069
3070/// Streaming sample-rate converter for mono `f32` PCM.
3071///
3072/// Audio models want their own rate — [`MtmdContext::audio_sample_rate`] says
3073/// which — and a microphone or file rarely matches it. This converts between
3074/// the two a block at a time, keeping the filter state across calls, so a
3075/// realtime stream can be fed in as it arrives rather than buffered whole.
3076///
3077/// One instance per stream: the state is what makes consecutive blocks join
3078/// without a seam, so sharing one across two streams would interleave them.
3079///
3080/// Wraps `mtmd_helper_resampler_*`, new in `b12388`.
3081///
3082/// # Examples
3083///
3084/// ```no_run
3085/// # use llama_cpp_4::mtmd::{MtmdContext, MtmdResampler};
3086/// # fn f(mtmd: &MtmdContext, mic_chunks: impl Iterator<Item = Vec<f32>>)
3087/// # -> Result<(), Box<dyn std::error::Error>> {
3088/// let mut resampler = MtmdResampler::new(48_000, mtmd.audio_sample_rate())?;
3089/// let mut pcm = Vec::new();
3090/// for chunk in mic_chunks {
3091/// pcm.extend_from_slice(resampler.process(&chunk)?);
3092/// }
3093/// # Ok(())
3094/// # }
3095/// ```
3096pub struct MtmdResampler {
3097 ptr: NonNull<sys::mtmd_helper_resampler>,
3098}
3099
3100impl std::fmt::Debug for MtmdResampler {
3101 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3102 f.debug_struct("MtmdResampler").finish_non_exhaustive()
3103 }
3104}
3105
3106impl Drop for MtmdResampler {
3107 fn drop(&mut self) {
3108 // SAFETY: this runs once from `Drop` on a non-null handle, and nothing
3109 // reads it afterwards.
3110 unsafe { sys::mtmd_helper_resampler_free(self.ptr.as_ptr()) }
3111 }
3112}
3113
3114impl MtmdResampler {
3115 /// Open a resampler converting `rate_in` Hz to `rate_out` Hz.
3116 ///
3117 /// Equal rates are allowed and pass samples through.
3118 ///
3119 /// # Errors
3120 ///
3121 /// Returns [`MtmdError::ResamplerInitFailed`] when llama.cpp cannot build
3122 /// a converter for that pair — a non-positive rate, say.
3123 pub fn new(rate_in: i32, rate_out: i32) -> Result<Self> {
3124 // SAFETY: no pointer is involved; both arguments are plain scalars and
3125 // the result is checked for null before being wrapped.
3126 let ptr = unsafe { sys::mtmd_helper_resampler_init(rate_in, rate_out) };
3127 NonNull::new(ptr)
3128 .map(|ptr| Self { ptr })
3129 .ok_or(MtmdError::ResamplerInitFailed { rate_in, rate_out })
3130 }
3131
3132 /// Convert one block, returning the samples produced so far.
3133 ///
3134 /// The result is often shorter or longer than `input` and may be empty:
3135 /// the converter holds back whatever it needs to join the next block
3136 /// cleanly. Feeding an empty slice is allowed and simply drains nothing.
3137 ///
3138 /// The returned slice borrows the resampler's own buffer, which the next
3139 /// call overwrites. `&mut self` here and `&[f32]` out is what makes the
3140 /// borrow checker enforce that rather than leaving it to a doc comment —
3141 /// copy out (as the example on this type does) to keep the samples.
3142 ///
3143 /// `input` is borrowed for the same region as the result, which is not
3144 /// over-tight: when the two rates are equal upstream passes the input
3145 /// buffer straight back out, so the result can alias `input` rather than
3146 /// the resampler's buffer. Tying both to one lifetime is what keeps that
3147 /// case from handing back a dangling slice.
3148 ///
3149 /// # Errors
3150 ///
3151 /// Returns [`MtmdError::ResampleError`] if llama.cpp reports a negative
3152 /// code.
3153 pub fn process<'a>(&'a mut self, input: &'a [f32]) -> Result<&'a [f32]> {
3154 let mut out: *const f32 = std::ptr::null();
3155 // SAFETY: an exclusive `&mut self` gives a live, non-null resampler.
3156 // `input`'s pointer and length are passed together, so the read stays
3157 // in bounds, and `out` is a stack local upstream writes through.
3158 let n = unsafe {
3159 sys::mtmd_helper_resampler_process(
3160 self.ptr.as_ptr(),
3161 input.as_ptr(),
3162 input.len(),
3163 &raw mut out,
3164 )
3165 };
3166 if n < 0 {
3167 return Err(MtmdError::ResampleError(n));
3168 }
3169 let n = usize::try_from(n).map_err(|_| MtmdError::ResampleError(n))?;
3170 if n == 0 || out.is_null() {
3171 return Ok(&[]);
3172 }
3173 // SAFETY: `out` is non-null and points at `n` initialised samples —
3174 // either the resampler's own output buffer, which upstream just
3175 // filled, or `input` itself when the rates match and upstream passes
3176 // the block through. The returned lifetime is tied to both the
3177 // exclusive borrow of `self` and the borrow of `input`, so it cannot
3178 // outlive whichever one the data lives in.
3179 Ok(unsafe { slice::from_raw_parts(out, n) })
3180 }
3181}
3182
3183// SAFETY: the resampler owns its state outright and nothing in it is tied to
3184// the thread that created it.
3185unsafe impl Send for MtmdResampler {}
3186
3187// SAFETY: the only method that touches the converter state takes `&mut self`,
3188// so a shared reference cannot reach it.
3189unsafe impl Sync for MtmdResampler {}