Skip to content

Local, full Windows search replacement, clipboard manager, and launcher: files, apps, settings and semantic media search with Google's EmbeddingGemma 2.

Add native CPU/GPU video decoding and polish search layouts

ampersandru602ddce7b887
diff --git a/README.md b/README.md
index 2c144eb..fa11719 100644
--- a/README.md
+++ b/README.md
@@ -97,10 +97,10 @@ Parakeet provides **English speech-to-text**, independently of semantic search.
| [Tesseract OCR](https://github.com/UB-Mannheim/tesseract/wiki) — optional | Reads exact words in screenshots and scanned PDFs | 50 MB |
| [OCR language packs](https://github.com/tesseract-ocr/tessdata_fast) — optional | Enables OCR for selected languages | English 4 MB |
| Parakeet speech runtime — optional | Runs the dictation model above | CPU ~19 MB; CUDA and libraries ~1.83 GB |
-| [FFmpeg / FFprobe / FFplay](https://ffmpeg.org/) | Extracts media frames/audio and plays matched moments; bundled | About 150 MB unpacked |
+| [FFmpeg / FFprobe / FFplay](https://ffmpeg.org/) | Compatibility video decoder, audio extraction and matched-moment playback; bundled | About 150 MB unpacked |
| [PDFium](https://pdfium.googlesource.com/pdfium/) | PDF extraction and page previews; bundled | About 10–25 MB |
-Install only the runtime for your hardware. OCR is optional for image meaning searches; it helps with exact text. FFmpeg and the encoder are needed for media processing.
+Install only the runtime for your hardware. OCR is optional for image meaning searches; it helps with exact text. Windows native decoding is the default for video frames, with separate CPU/GPU settings and optional FFmpeg fallback. FFmpeg is still used for audio extraction/playback; semantic media search also needs the matching encoder.
**Download trouble?** Setup caches official catalogs and retries temporary failures. Rate-limit messages identify GitHub (runtimes) or Hugging Face (models) and suggest when to retry. Optional **GitHub / Hugging Face download tokens** are in **Hardware → Optional download tokens**; save them before retrying. They are protected by your Windows account and sent only to their own service. Interrupted downloads retain partial files for resume, and checksums are still required. You can also select an existing runtime/model manually.
diff --git a/docs/RETRIEVAL.md b/docs/RETRIEVAL.md
index 74f71aa..3e7f8c6 100644
--- a/docs/RETRIEVAL.md
+++ b/docs/RETRIEVAL.md
@@ -35,3 +35,28 @@ Run `windows/qa_retrieval.py` to reproduce the generated-file checks. `windows/q
| RAR, legacy DOC/XLS/PPT, other weights/binaries | Filename search only |
Abstract recollections, natural photos and long-media accuracy still depend on the model, input quality and sampling. The generated test counts above must not be presented as a real-world accuracy benchmark or as DigUp's published results. Update the index after upgrading to enable the new extraction and security options.
+
+## Video decoding
+
+In Sources, **Video decoder** defaults to **Windows (native)**. It uses a per-file Media Foundation reader, seeking to sampled moments and releasing each frame after encoding. It does not upload entire videos or retain decoded videos in memory. **Video decoding device** is separate from embedding inference: Auto follows the selected CPU/GPU hardware preference, CPU uses software decoding, and GPU configures a D3D11 device manager. A separate adapter selector is available. Actual acceleration depends on installed codecs and drivers; Auto can fall back to CPU.
+
+Choose **FFmpeg** for compatibility, or enable **Use FFmpeg if Windows cannot decode this video**. This fallback is attempted before emitting frames, preventing duplicate partial indexing. FFmpeg also honors the video CPU/GPU choice and limits decoder/filter/encoder threads. Audio moment extraction still uses FFmpeg when enabled. Silent native videos do not need an FFprobe subprocess.
+
+EmbeddingGemma's video support still uses sampled decoded frames. Passing a video path to SentenceTransformers hides that preprocessing; llama.cpp's direct `input_video` support also needs FFmpeg. The frame-based route preserves precise searchable moments without sending whole videos or exceeding the embedding server's context window. See [Google's video sampling guidance](https://developers.googleblog.com/en/embeddinggemma-2-the-developer-guide/), [llama.cpp multimodal inputs](https://github.com/ggml-org/llama.cpp/tree/master/tools/server), and [Windows Source Reader](https://learn.microsoft.com/en-us/windows/win32/medfound/processing-media-data-with-the-source-reader).
+
+### Local decoder measurements
+
+Illustrative Windows x64 release-build measurements: three runs per mode, five-second sampling, process startup included, no embedding inference. Clips are generated H.264 color/test patterns (24 seconds at 640×360; 20 seconds at 1920×1080), with one-second keyframes. Wall time is median; RAM is maximum observed process-tree RSS (including an FFmpeg child where applicable), not VRAM. Pipelines use their own JPEG encoders; codec, keyframe interval, hardware and system load affect results.
+
+| Clip | Decoder | Device | Median time | Peak RAM | Median CPU time |
+| --- | --- | --- | --- | --- | --- |
+| 360p / 5 frames | Windows (native) | CPU | 0.323 s | 36.0 MiB | 0.141 s |
+| 360p / 5 frames | Windows (native) | GPU | 0.575 s | 74.6 MiB | 0.359 s |
+| 360p / 5 frames | FFmpeg | CPU | 0.279 s | 47.4 MiB | 0.219 s |
+| 360p / 5 frames | FFmpeg | GPU | 0.709 s | 108.5 MiB | 0.484 s |
+| 1080p / 4 frames | Windows (native) | CPU | 0.366 s | 81.1 MiB | 0.328 s |
+| 1080p / 4 frames | Windows (native) | GPU | 0.604 s | 86.7 MiB | 0.391 s |
+| 1080p / 4 frames | FFmpeg | CPU | 0.632 s | 70.7 MiB | 0.953 s |
+| 1080p / 4 frames | FFmpeg | GPU | 1.185 s | 126.1 MiB | 0.750 s |
+
+GPU startup can outweigh decode savings on short clips; use CPU when it is faster for your workload. The native GPU route uses a D3D11 device manager and multithread protection; supported Windows codecs/drivers determine hardware acceleration. The default native GPU above was verified as an NVIDIA GeForce RTX 5080 (D3D11 video decoding, not CUDA). FFmpeg Auto selected DXVA2. Explicit AMD Radeon(TM) Graphics adapter tests also passed: native decoding took 0.429 s / 74.3 MiB at 360p and 0.537 s / 154.3 MiB at 1080p; FFmpeg D3D11VA took 1.190 s / 90.5 MiB and 2.764 s / 180.8 MiB respectively. These are separate video-device choices, independent of the embedding GPU. Native output is resized to at most 1024 pixels per dimension before JPEG encoding where the installed decoder supports it. Media Foundation is loaded on demand; systems without it can use the FFmpeg fallback.
diff --git a/native/Cargo.toml b/native/Cargo.toml
index a532543..aff9e6d 100644
--- a/native/Cargo.toml
+++ b/native/Cargo.toml
@@ -46,7 +46,7 @@ zip = { version = "4", default-features = false, features = ["deflate"] }
embed-resource = "3"
[target.'cfg(windows)'.dependencies]
windows-numerics = "0.2"
-windows = { version = "0.61", features = ["UI_Composition", "UI_Composition_Desktop", "System", "Win32_System_WinRT", "Win32_System_WinRT_Composition", "Win32_Foundation", "Win32_Media_Audio", "Win32_Security", "Win32_Security_Cryptography", "Win32_System_Memory", "Win32_System_LibraryLoader", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Com", "Win32_System_Ole", "Win32_System_Variant", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_UI_Accessibility", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_Performance", "Win32_System_Power", "Win32_System_ProcessStatus", "Win32_System_DataExchange", "Win32_System_SystemInformation", "Win32_Graphics_Gdi", "Win32_Graphics_Dwm", "Win32_Security_Authorization", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock"] }
+windows = { version = "0.61", features = ["UI_Composition", "UI_Composition_Desktop", "System", "Win32_System_WinRT", "Win32_System_WinRT_Composition", "Win32_Foundation", "Win32_Media_Audio", "Win32_Media_MediaFoundation", "Win32_System_Com_StructuredStorage", "Win32_Graphics_Direct3D11", "Win32_Graphics_Direct3D10", "Win32_Graphics_Direct3D", "Win32_Graphics_Dxgi", "Win32_Graphics_Dxgi_Common", "Win32_Security", "Win32_Security_Cryptography", "Win32_System_Memory", "Win32_System_LibraryLoader", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Com", "Win32_System_Ole", "Win32_System_Variant", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_Shell_Common", "Win32_UI_Accessibility", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Ioctl", "Win32_System_Performance", "Win32_System_Power", "Win32_System_ProcessStatus", "Win32_System_DataExchange", "Win32_System_SystemInformation", "Win32_Graphics_Gdi", "Win32_Graphics_Dwm", "Win32_Security_Authorization", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock"] }
[dev-dependencies]
[profile.release]
lto = "thin"
diff --git a/native/build.rs b/native/build.rs
index 20158e4..58ba3ba 100644
--- a/native/build.rs
+++ b/native/build.rs
@@ -2,6 +2,13 @@ fn main() {
println!("cargo:rerun-if-changed=assets/vectordash.ico");
println!("cargo:rerun-if-changed=assets/app.rc");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
+ if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") {
+ // Media Foundation is optional on Windows N/Server. Check availability
+ // before calling it; missing media features must not prevent app startup.
+ println!("cargo:rustc-link-lib=delayimp");
+ println!("cargo:rustc-link-arg=/DELAYLOAD:mfplat.dll");
+ println!("cargo:rustc-link-arg=/DELAYLOAD:mfreadwrite.dll");
+ }
let version = std::env::var("CARGO_PKG_VERSION").unwrap();
let commas = format!("{},0", version.replace('.', ","));
let icon = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
diff --git a/native/src/app.rs b/native/src/app.rs
index 597c141..1ef8dc8 100644
--- a/native/src/app.rs
+++ b/native/src/app.rs
@@ -578,6 +578,9 @@ impl App {
if args.iter().any(|a| a == "--smoke-indexing") {
app.indexing = true;
}
+ if args.iter().any(|a| a == "--smoke-tts-busy") {
+ app.tts_busy = true;
+ }
if args.iter().any(|a| a == "--smoke-transcribing") {
app.dictation_busy = true;
app.dictation_status = "Transcribing...".into();
@@ -1990,7 +1993,13 @@ impl App {
.frame(false)
.background_color(Color32::TRANSPARENT)
.margin(egui::Margin {
- right: if self.tool == "Search" { 92 } else { 8 },
+ right: if self.tool == "Search" {
+ 92
+ } else if self.tool == "AI" {
+ 124
+ } else {
+ 8
+ },
..egui::Margin::symmetric(8, 8)
})
.lock_focus(true)
@@ -2043,6 +2052,34 @@ impl App {
},
);
}
+ if self.tool == "AI" && !recording {
+ let full = format!("AI: {}", self.saved_settings.llm_model);
+ let short = if full.chars().count() > 20 {
+ format!("{}…", full.chars().take(19).collect::<String>())
+ } else {
+ full.clone()
+ };
+ let label_rect = egui::Rect::from_min_max(
+ egui::pos2(
+ (response.rect.right() - 116.0).max(response.rect.left()),
+ response.rect.top(),
+ ),
+ response.rect.right_bottom() - egui::vec2(8.0, 0.0),
+ );
+ ui.painter().with_clip_rect(label_rect).text(
+ label_rect.right_center(),
+ egui::Align2::RIGHT_CENTER,
+ short,
+ egui::FontId::proportional(11.0),
+ ui.visuals().text_color(),
+ );
+ ui.interact(
+ label_rect,
+ egui::Id::new("ai-model-label"),
+ egui::Sense::hover(),
+ )
+ .on_hover_text(full);
+ }
if self.select_query && !recording {
self.select_query = false;
let id = egui::Id::new("query");
@@ -2210,14 +2247,22 @@ impl App {
self.stop_ai();
self.ai_error = Some("Request stopped".into());
}
- } else if ui
- .add_enabled(
- !self.query.trim().is_empty() && !self.dictation_busy,
- egui::Button::new("Send").min_size(egui::vec2(88.0, 34.0)),
- )
- .clicked()
- {
- self.ask_ai();
+ } else {
+ let enabled = !self.query.trim().is_empty() && !self.dictation_busy;
+ let accent = self.accent();
+ let send = ui.add_enabled(enabled,
+ egui::Button::new("Send")
+ .min_size(egui::vec2(88.0, 34.0))
+ .fill(accent.gamma_multiply(if enabled {0.35} else {0.12}))
+ .stroke(egui::Stroke::new(1.0, accent)),
+ );
+ // Static soft outline: no idle animation or extra repaint loop.
+ for (width, alpha) in [(5.0, 0.07), (3.0, 0.15)] {
+ ui.painter().rect_stroke(send.rect.expand(0.5), 14,
+ egui::Stroke::new(width, accent.gamma_multiply(alpha)),
+ egui::StrokeKind::Outside);
+ }
+ if send.clicked() { self.ask_ai(); }
}
if self.saved_settings.tts_enabled {ui.add(egui::Checkbox::new(
&mut self.read_aloud,
@@ -3067,7 +3112,8 @@ impl App {
ui.horizontal(|ui| {
ui.add(
egui::TextEdit::singleline(&mut self.manual_exclude)
- .hint_text("Enter a file or folder path"),
+ .hint_text("Enter a file or folder path")
+ .desired_width(320.0),
);
if ui.button("Add exclusion").clicked() && !self.manual_exclude.is_empty() {
self.s
@@ -3094,7 +3140,7 @@ impl App {
let mut remove = None;
let exclusion_list = egui::ScrollArea::vertical()
.id_salt("exclusion-list")
- .max_width(ui.available_width() * 0.88)
+ .max_width(ui.available_width().min(620.0))
.max_height(220.0)
.min_scrolled_height(if self.s.exclusions.is_empty() {
0.0
@@ -3109,10 +3155,12 @@ impl App {
for (i, p) in self.s.exclusions.iter().enumerate() {
ui.horizontal(|ui| {
ui.checkbox(&mut self.exclusion_selected[i], "");
- ui.add_sized(
- [(ui.available_width() - 100.0).max(100.0), 22.0],
- egui::Label::new(p).truncate(),
+ ui.allocate_ui_with_layout(
+ egui::vec2((ui.available_width() - 100.0).clamp(100.0, 420.0), 22.0),
+ egui::Layout::left_to_right(egui::Align::Center),
+ |ui| ui.add(egui::Label::new(p).truncate()),
)
+ .response
.on_hover_text(p);
if ui.small_button("Remove").clicked() {
remove = Some(i);
@@ -3192,6 +3240,46 @@ impl App {
"Embed PDF page images as well as page text",
);
if self.s.index_video {
+ combo(
+ ui,
+ "video-decoder",
+ &mut self.s.video_decoder,
+ &["Windows (native)", "FFmpeg"],
+ );
+ combo(
+ ui,
+ "video-decode-device",
+ &mut self.s.video_decode_device,
+ &["Auto", "CPU", "GPU"],
+ );
+ ui.weak("Video decoding is separate from embedding inference. Auto follows CPU/GPU hardware preference; available codecs determine acceleration.");
+ if crate::native_video::gpu_requested(&self.s) {
+ let adapters = crate::native_video::adapters();
+ let name = adapters
+ .iter()
+ .find(|(id, _)| id == &self.s.video_gpu)
+ .map(|(_, name)| name.as_str())
+ .unwrap_or("Windows default GPU");
+ egui::ComboBox::from_id_salt("video-gpu")
+ .selected_text(name)
+ .show_ui(ui, |ui| {
+ ui.selectable_value(
+ &mut self.s.video_gpu,
+ String::new(),
+ "Windows default GPU",
+ );
+ for (id, name) in adapters {
+ ui.selectable_value(&mut self.s.video_gpu, id, name);
+ }
+ });
+ }
+ if self.s.video_decoder != "FFmpeg" {
+ ui.checkbox(
+ &mut self.s.video_ffmpeg_fallback,
+ "Use FFmpeg if Windows cannot decode this video",
+ );
+ }
+ ui.weak("Native Windows decoding avoids FFmpeg for video frames. Audio extraction still uses FFmpeg when Index audio moments is enabled.");
ui.add(
egui::Slider::new(&mut self.s.video_interval, 1.0..=60.0)
.text("Video frame sampling interval (seconds)"),
@@ -4186,6 +4274,8 @@ impl App {
self.clipboard_texture = None;
self.clipboard_preview_id = -1;
self.tool = tool.into();
+ // Empty tools can have different compact heights even when emptiness stays true.
+ self.popup_size_state = None;
self.large_preview = false;
if tool == "Search" {
self.model_warm_attempted = false;
@@ -4295,6 +4385,7 @@ impl App {
self.tts_job += 1;
let id = self.tts_job;
self.tts_busy = true;
+ self.ai_follow_bottom = true;
self.tts_status = String::new();
self.tts_cancel = Arc::new(AtomicBool::new(false));
let cancel = self.tts_cancel.clone();
@@ -4426,8 +4517,9 @@ impl App {
self.ai_scroll = 0.0;
let output = egui::ScrollArea::vertical()
.id_salt("ai-answer")
- .stick_to_bottom(self.ai_busy)
- .max_height(ui.available_height().max(80.0))
+ .stick_to_bottom(self.ai_busy || self.tts_busy)
+ .min_scrolled_height(0.0)
+ .max_height(ui.available_height().max(0.0))
.show(ui, |ui| {
for message in &self.ai_messages {
ui.label(
@@ -4515,6 +4607,14 @@ impl App {
ui.scroll_with_delta(egui::vec2(0.0, scroll));
}
});
+ if self.smoke.is_some() {
+ ctx.data_mut(|d| {
+ d.insert_temp(
+ egui::Id::new("qa-answer-bottom"),
+ output.inner_rect.bottom(),
+ )
+ });
+ }
self.ai_scroll_offset = output.state.offset.y;
return;
}
@@ -5606,6 +5706,16 @@ impl eframe::App for App {
.max(now.duration_since(self.last_frame).as_secs_f64() * 1000.0);
self.last_frame = now;
self.frames += 1;
+ if self.smoke.is_some() && std::env::args().any(|a| a == "--smoke-tool-roundtrip") {
+ if self.frames == 8 {
+ self.switch_tool("AI");
+ }
+ if self.frames == 15 {
+ let height = ctx.content_rect().height();
+ ctx.data_mut(|d| d.insert_temp(egui::Id::new("qa-ai-height"), height));
+ self.switch_tool("Search");
+ }
+ }
if self.page != 2 {
self.hardware_open = false;
}
@@ -5853,6 +5963,11 @@ impl eframe::App for App {
egui::TopBottomPanel::bottom("status")
.frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(20, 9)))
.show(ctx, |ui| {
+ if self.smoke.is_some() {
+ ctx.data_mut(|d| {
+ d.insert_temp(egui::Id::new("qa-footer-top"), ui.max_rect().top() - 9.0)
+ });
+ }
if self.page == 0 {
if !self.tts_status.is_empty() {
ui.label(&self.tts_status);
@@ -5875,7 +5990,6 @@ impl eframe::App for App {
ui.label(&self.dictation_status);
}
if self.tool == "AI" {
- ui.weak(format!("AI model: {}", self.saved_settings.llm_model));
if let Some(error) = &self.ai_error {
ui.colored_label(Color32::LIGHT_RED, error);
}
@@ -6556,6 +6670,15 @@ impl eframe::App for App {
data["exclusion_list"] = serde_json::json!(
ctx.data(|d| d.get_temp::<[f32; 2]>(egui::Id::new("qa-exclusion")))
);
+ data["answer_bottom"] = serde_json::json!(
+ ctx.data(|d| d.get_temp::<f32>(egui::Id::new("qa-answer-bottom")))
+ );
+ data["footer_top"] = serde_json::json!(
+ ctx.data(|d| d.get_temp::<f32>(egui::Id::new("qa-footer-top")))
+ );
+ data["ai_compact_height"] = serde_json::json!(
+ ctx.data(|d| d.get_temp::<f32>(egui::Id::new("qa-ai-height")))
+ );
data["window_size"] =
serde_json::json!([ctx.content_rect().width(), ctx.content_rect().height()]);
data["category"] = serde_json::json!(self.category);
diff --git a/native/src/config.rs b/native/src/config.rs
index 3016fa8..5d689a2 100644
--- a/native/src/config.rs
+++ b/native/src/config.rs
@@ -84,6 +84,10 @@ pub struct Settings {
pub max_run_minutes: u32,
pub schedule_history: Vec<String>,
pub video_interval: f32,
+ pub video_decoder: String,
+ pub video_decode_device: String,
+ pub video_gpu: String,
+ pub video_ffmpeg_fallback: bool,
pub pdf_visuals: bool,
pub visual_detail: String,
pub default_search_mode: String,
@@ -218,6 +222,10 @@ impl Default for Settings {
max_run_minutes: 120,
schedule_history: vec![],
video_interval: 5.0,
+ video_decoder: "Windows (native)".into(),
+ video_decode_device: "Auto".into(),
+ video_gpu: String::new(),
+ video_ffmpeg_fallback: true,
pdf_visuals: false,
visual_detail: "Balanced".into(),
default_search_mode: "Both".into(),
diff --git a/native/src/content.rs b/native/src/content.rs
index 4d339fb..6437dac 100644
--- a/native/src/content.rs
+++ b/native/src/content.rs
@@ -397,98 +397,17 @@ fn media_segments(
checkpoint: &dyn Fn() -> Result<()>,
) -> Result<Vec<Segment>> {
let mut records = vec![];
- let video = is_video(&extension(path));
- let mut c = Command::new(ffmpeg(s)?);
- c.args(["-nostdin", "-hide_banner", "-i"]).arg(path);
- hidden(&mut c);
- let probe = c.output()?;
- let meta = String::from_utf8_lossy(&probe.stderr);
- let duration = meta
- .split("Duration: ")
- .nth(1)
- .and_then(|x| x.split(',').next())
- .and_then(|x| {
- let n: Vec<f32> = x.trim().split(':').filter_map(|p| p.parse().ok()).collect();
- if n.len() == 3 {
- Some(n[0] * 3600.0 + n[1] * 60.0 + n[2])
- } else {
- None
- }
- })
- .context("Media duration unavailable")?;
- let interval = if video { 5.0 } else { 30.0 };
- for i in 0..(duration / interval).ceil().min(10000.0) as u32 {
- checkpoint()?;
- let sec = i as f32 * interval;
- let mut c = Command::new(ffmpeg(s)?);
- c.args(["-nostdin", "-v", "error", "-ss", &sec.to_string(), "-i"])
- .arg(path);
- if video {
- if !s.index_video {
- break;
- }
- c.args([
- "-frames:v",
- "1",
- "-vf",
- "scale='min(1024,iw)':-2",
- "-f",
- "image2pipe",
- "-vcodec",
- "mjpeg",
- "-",
- ]);
- } else {
- if !s.index_audio {
- break;
- }
- c.args(["-t", "30", "-ac", "1", "-ar", "16000", "-f", "wav", "-"]);
- }
- hidden(&mut c);
- let out = c.output()?;
- if out.status.success() {
- records.push(Segment {
- kind: if video { "video" } else { "audio" }.into(),
- text: String::new(),
- page: 0,
- seconds: sec,
- line: 0,
- media: out.stdout,
- });
- }
- if records.len() > 2000 {
- anyhow::bail!(
- "Media contains too many segments for one file; use a smaller source or adjust sampling"
- );
- }
- }
- if video && s.index_audio {
- for i in 0..(duration / 30.0).ceil().min(2000.0) as u32 {
- checkpoint()?;
- let seconds = i as f32 * 30.0;
- let mut c = Command::new(ffmpeg(s)?);
- c.args(["-nostdin", "-v", "error", "-ss", &seconds.to_string(), "-i"])
- .arg(path)
- .args([
- "-t", "30", "-vn", "-ac", "1", "-ar", "16000", "-f", "wav", "-",
- ]);
- hidden(&mut c);
- let out = c.output()?;
- if out.status.success() {
- records.push(Segment {
- kind: "video_audio".into(),
- text: String::new(),
- page: 0,
- seconds,
- line: 0,
- media: out.stdout,
- });
- }
- }
- }
-
+ stream(path, s, checkpoint, &mut |segment| {
+ anyhow::ensure!(
+ records.len() < 2000,
+ "Media contains too many segments for one file"
+ );
+ records.push(segment);
+ Ok(())
+ })?;
Ok(records)
}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -556,7 +475,26 @@ pub fn ocr_bytes(bytes: &[u8], s: &Settings) -> Result<String> {
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
pub fn video_frame(path: &Path, seconds: f32, s: &Settings) -> Result<Vec<u8>> {
+ if s.video_decoder != "FFmpeg" {
+ let result = crate::native_video::open(path, s)
+ .and_then(|reader| reader.frame(seconds, &|| Ok(())))
+ .and_then(|frame| {
+ frame
+ .map(|(_, bytes)| bytes)
+ .context("No video frame at this time")
+ });
+ match result {
+ Ok(bytes) => return Ok(bytes),
+ Err(error) if !s.video_ffmpeg_fallback => {
+ return Err(error.context(
+ "Windows video decoding failed; enable FFmpeg fallback or choose FFmpeg",
+ ));
+ }
+ Err(_) => {}
+ }
+ }
let mut c = Command::new(ffmpeg(s)?);
+ crate::native_video::ffmpeg_device(&mut c, s);
c.args([
"-nostdin",
"-v",
@@ -575,6 +513,8 @@ pub fn video_frame(path: &Path, seconds: f32, s: &Settings) -> Result<Vec<u8>> {
"image2pipe",
"-vcodec",
"mjpeg",
+ "-threads",
+ "2",
"-",
]);
hidden(&mut c);
@@ -603,8 +543,56 @@ pub fn stream(
return Ok(());
}
use std::process::Stdio;
- if is_video(&ext) && s.index_video {
+ let mut native_frames = false;
+ let mut native_audio = None;
+ if is_video(&ext) && s.index_video && s.video_decoder != "FFmpeg" {
+ let mut emitted = 0;
+ let result = (|| -> Result<()> {
+ let reader = crate::native_video::open(path, s)?;
+ native_audio = Some(reader.has_audio());
+ let interval = s.video_interval.clamp(1.0, 60.0);
+ for frame in 0..100000u32 {
+ checkpoint()?;
+ let seconds = frame as f32 * interval;
+ if reader.duration().is_some_and(|d| seconds >= d) {
+ break;
+ }
+ let Some((seconds, media)) = reader.frame(seconds, checkpoint)? else {
+ break;
+ };
+ emit(Segment {
+ kind: "video".into(),
+ text: String::new(),
+ page: 0,
+ seconds,
+ line: 0,
+ media,
+ })?;
+ emitted += 1;
+ }
+ Ok(())
+ })();
+ match result {
+ Ok(()) => native_frames = true,
+ Err(error) if emitted == 0 && s.video_ffmpeg_fallback => {
+ checkpoint()?;
+ emit(Segment::text(
+ "warning",
+ format!("Windows video decoder unavailable; using FFmpeg fallback: {error}"),
+ 0,
+ 0,
+ ))?;
+ }
+ Err(error) => {
+ return Err(error.context(
+ "Windows video decoding failed; choose FFmpeg for unsupported codecs",
+ ));
+ }
+ }
+ }
+ if is_video(&ext) && s.index_video && !native_frames {
let mut c = Command::new(ffmpeg(s)?);
+ crate::native_video::ffmpeg_device(&mut c, s);
c.args(["-nostdin", "-v", "error", "-i"])
.arg(path)
.args([
@@ -618,6 +606,8 @@ pub fn stream(
"image2pipe",
"-vcodec",
"mjpeg",
+ "-threads",
+ "2",
"-",
])
.stdout(Stdio::piped())
@@ -655,8 +645,8 @@ pub fn stream(
anyhow::ensure!(status.success(), "Video decoder failed");
}
// Silent videos are valid: do not discard their frames because no audio exists.
- let mut has_audio = true;
- if is_video(&ext) && s.index_audio {
+ let mut has_audio = native_audio.unwrap_or(true);
+ if is_video(&ext) && s.index_audio && native_audio.is_none() {
let decoder = ffmpeg(s)?;
let probe = Path::new(&decoder).with_file_name("ffprobe.exe");
if probe.exists() {
diff --git a/native/src/main.rs b/native/src/main.rs
index 25028ed..e539f92 100644
--- a/native/src/main.rs
+++ b/native/src/main.rs
@@ -17,6 +17,7 @@ mod journal;
mod launcher;
mod mcp;
mod models;
+mod native_video;
mod pdf;
mod platform;
mod previews;
diff --git a/native/src/native_video.rs b/native/src/native_video.rs
new file mode 100644
index 0000000..b537b73
--- /dev/null
+++ b/native/src/native_video.rs
@@ -0,0 +1,401 @@
+//! Windows video frames through Media Foundation. Readers are scoped to one file;
+//! only the sampled frame is copied/encoded, never the whole video.
+use crate::config::Settings;
+use anyhow::{Context, Result};
+use std::path::Path;
+pub fn gpu_requested(s: &Settings) -> bool {
+ s.video_decode_device == "GPU"
+ || (s.video_decode_device == "Auto" && s.hardware != "CPU / system RAM")
+}
+pub fn ffmpeg_device(command: &mut std::process::Command, s: &Settings) {
+ command.args(["-threads", "2", "-filter_threads", "1"]);
+ if !gpu_requested(s) {
+ command.args(["-hwaccel", "none"]);
+ } else if !s.video_gpu.is_empty() {
+ command.args(["-hwaccel", "d3d11va", "-hwaccel_device", &s.video_gpu]);
+ } else {
+ command.args(["-hwaccel", "auto"]);
+ }
+}
+#[cfg(windows)]
+mod win {
+ use super::*;
+ use windows::{
+ Win32::{
+ Graphics::{Direct3D::*, Direct3D11::*, Dxgi::*},
+ Media::MediaFoundation::*,
+ System::Com::{
+ COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize,
+ StructuredStorage::PROPVARIANT,
+ },
+ },
+ core::{GUID, Interface, PCWSTR},
+ };
+ struct Platform {
+ com: bool,
+ mf: bool,
+ modules: Vec<windows::Win32::Foundation::HMODULE>,
+ }
+ impl Platform {
+ fn start() -> Result<Self> {
+ unsafe {
+ let hr = CoInitializeEx(None, COINIT_MULTITHREADED);
+ let mut platform = Self {
+ com: hr.is_ok(),
+ mf: false,
+ modules: vec![],
+ };
+ if hr.is_err() && hr.0 != 0x80010106u32 as i32 {
+ hr.ok()?;
+ }
+ use windows::Win32::System::LibraryLoader::{
+ LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
+ };
+ for library in [
+ windows::core::w!("mfplat.dll"),
+ windows::core::w!("mfreadwrite.dll"),
+ ] {
+ platform.modules.push(LoadLibraryExW(
+ library,
+ None,
+ LOAD_LIBRARY_SEARCH_SYSTEM32,
+ )?);
+ }
+ MFStartup(MF_VERSION, MFSTARTUP_FULL)?;
+ platform.mf = true;
+ Ok(platform)
+ }
+ }
+ }
+ impl Drop for Platform {
+ fn drop(&mut self) {
+ unsafe {
+ if self.mf {
+ let _ = MFShutdown();
+ }
+ if self.com {
+ CoUninitialize();
+ }
+ for module in self.modules.drain(..).rev() {
+ let _ = windows::Win32::Foundation::FreeLibrary(module);
+ }
+ }
+ }
+ }
+ pub fn adapters() -> Vec<(String, String)> {
+ static CACHE: std::sync::OnceLock<Vec<(String, String)>> = std::sync::OnceLock::new();
+ CACHE
+ .get_or_init(|| unsafe {
+ let Ok(factory) = CreateDXGIFactory1::<IDXGIFactory1>() else {
+ return vec![];
+ };
+ (0..16)
+ .map_while(|i| factory.EnumAdapters1(i).ok().map(|a| (i, a)))
+ .filter_map(|(i, a)| {
+ let d = a.GetDesc1().ok()?;
+ if d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
+ return None;
+ }
+ let n = d
+ .Description
+ .iter()
+ .position(|v| *v == 0)
+ .unwrap_or(d.Description.len());
+ Some((i.to_string(), String::from_utf16_lossy(&d.Description[..n])))
+ })
+ .collect()
+ })
+ .clone()
+ }
+ pub struct Reader {
+ source: IMFSourceReader,
+ _manager: Option<IMFDXGIDeviceManager>,
+ _platform: Platform,
+ }
+ impl Reader {
+ pub fn open(path: &Path, s: &Settings) -> Result<Self> {
+ unsafe {
+ let platform = Platform::start()?;
+ let mut attrs = None;
+ MFCreateAttributes(&mut attrs, 5)?;
+ let attrs = attrs.context("Video attributes unavailable")?;
+ attrs.SetUINT32(&MF_SOURCE_READER_ENABLE_ADVANCED_VIDEO_PROCESSING, 1)?;
+ attrs.SetUINT32(&MF_LOW_LATENCY, 1)?;
+ let manager = if gpu_requested(s) {
+ let factory = CreateDXGIFactory1::<IDXGIFactory1>()?;
+ let adapter = if let Ok(index) = s.video_gpu.parse::<u32>() {
+ Some(factory.EnumAdapters1(index)?.cast::<IDXGIAdapter>()?)
+ } else {
+ None
+ };
+ let mut device = None;
+ D3D11CreateDevice(
+ adapter.as_ref(),
+ if adapter.is_some() {
+ D3D_DRIVER_TYPE_UNKNOWN
+ } else {
+ D3D_DRIVER_TYPE_HARDWARE
+ },
+ windows::Win32::Foundation::HMODULE::default(),
+ D3D11_CREATE_DEVICE_VIDEO_SUPPORT | D3D11_CREATE_DEVICE_BGRA_SUPPORT,
+ None,
+ D3D11_SDK_VERSION,
+ Some(&mut device),
+ None,
+ None,
+ )?;
+ let device = device.context("Video GPU unavailable")?;
+ // Media Foundation invokes the D3D device from its own threads.
+ // Protect the immediate context or hardware transforms can deadlock.
+ let context = device.GetImmediateContext()?;
+ let multithread = context
+ .cast::<windows::Win32::Graphics::Direct3D10::ID3D10Multithread>(
+ )?;
+ let _ = multithread.SetMultithreadProtected(true);
+
+ let mut token = 0;
+ let mut manager = None;
+ MFCreateDXGIDeviceManager(&mut token, &mut manager)?;
+ let manager = manager.context("Video device manager unavailable")?;
+ manager.ResetDevice(&device, token)?;
+ attrs.SetUnknown(&MF_SOURCE_READER_D3D_MANAGER, &manager)?;
+ attrs.SetUINT32(&MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 1)?;
+ Some(manager)
+ } else {
+ attrs.SetUINT32(&MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS, 0)?;
+ None
+ };
+ let url = path
+ .as_os_str()
+ .to_string_lossy()
+ .encode_utf16()
+ .chain(Some(0))
+ .collect::<Vec<_>>();
+ let source = MFCreateSourceReaderFromURL(PCWSTR(url.as_ptr()), &attrs)?;
+ source.SetStreamSelection(MF_SOURCE_READER_ALL_STREAMS.0 as u32, false)?;
+ source.SetStreamSelection(MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32, true)?;
+ let ty = MFCreateMediaType()?;
+ ty.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?;
+ ty.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_RGB32)?;
+ // Request the embedding thumbnail size from Windows' video processor,
+ // avoiding full-resolution RGB buffer pools and a second CPU resize.
+ let native =
+ source.GetNativeMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32, 0)?;
+ let size = native.GetUINT64(&MF_MT_FRAME_SIZE)?;
+ let (w, h) = ((size >> 32) as u32, size as u32);
+ if w.max(h) > 1024 {
+ let scale = 1024.0 / w.max(h) as f64;
+ let width = ((w as f64 * scale).round() as u32).max(2) & !1;
+ let height = ((h as f64 * scale).round() as u32).max(2) & !1;
+ ty.SetUINT64(&MF_MT_FRAME_SIZE, ((width as u64) << 32) | height as u64)?;
+ }
+ if source
+ .SetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32, None, &ty)
+ .is_err()
+ {
+ // Some Windows codecs cannot scale in the source reader.
+ ty.DeleteItem(&MF_MT_FRAME_SIZE)?;
+ source.SetCurrentMediaType(
+ MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32,
+ None,
+ &ty,
+ )?;
+ }
+ Ok(Self {
+ source,
+ _manager: manager,
+ _platform: platform,
+ })
+ }
+ }
+ pub fn has_audio(&self) -> bool {
+ unsafe {
+ self.source
+ .GetNativeMediaType(MF_SOURCE_READER_FIRST_AUDIO_STREAM.0 as u32, 0)
+ .is_ok()
+ }
+ }
+ pub fn duration(&self) -> Option<f32> {
+ unsafe {
+ let value = self
+ .source
+ .GetPresentationAttribute(
+ MF_SOURCE_READER_MEDIASOURCE.0 as u32,
+ &MF_PD_DURATION,
+ )
+ .ok()?;
+ i64::try_from(&value).ok().map(|v| v as f32 / 10_000_000.0)
+ }
+ }
+ pub fn frame(
+ &self,
+ seconds: f32,
+ checkpoint: &dyn Fn() -> Result<()>,
+ ) -> Result<Option<(f32, Vec<u8>)>> {
+ unsafe {
+ checkpoint()?;
+ let target = (seconds.max(0.0) as f64 * 10_000_000.0) as i64;
+ self.source
+ .SetCurrentPosition(&GUID::zeroed(), &PROPVARIANT::from(target))?;
+ for _ in 0..100000 {
+ checkpoint()?;
+ let mut flags = 0;
+ let mut stamp = 0;
+ let mut sample = None;
+ self.source.ReadSample(
+ MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32,
+ 0,
+ None,
+ Some(&mut flags),
+ Some(&mut stamp),
+ Some(&mut sample),
+ )?;
+ if flags & MF_SOURCE_READERF_ENDOFSTREAM.0 as u32 != 0 {
+ return Ok(None);
+ }
+ if stamp < target {
+ continue;
+ }
+ let Some(sample) = sample else { continue };
+ let ty = self
+ .source
+ .GetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM.0 as u32)?;
+ let size = ty.GetUINT64(&MF_MT_FRAME_SIZE)?;
+ let (w, h) = ((size >> 32) as u32, size as u32);
+ anyhow::ensure!(
+ w > 0 && h > 0 && (w as u64 * h as u64) <= 16_777_216,
+ "Native video frame exceeds size limit"
+ );
+ let buffer = sample.ConvertToContiguousBuffer()?;
+ let stride = ty.GetUINT32(&MF_MT_DEFAULT_STRIDE).unwrap_or(w * 4) as i32;
+ let mut ptr = std::ptr::null_mut();
+ let mut len = 0;
+ buffer.Lock(&mut ptr, None, Some(&mut len))?;
+ struct Lock<'a>(&'a IMFMediaBuffer);
+ impl Drop for Lock<'_> {
+ fn drop(&mut self) {
+ unsafe {
+ let _ = self.0.Unlock();
+ }
+ }
+ }
+ let _lock = Lock(&buffer);
+ let pitch = stride.unsigned_abs() as usize;
+ anyhow::ensure!(
+ !ptr.is_null()
+ && pitch >= w as usize * 4
+ && pitch * (h as usize - 1) + w as usize * 4 <= len as usize,
+ "Invalid native video buffer"
+ );
+ let bytes = std::slice::from_raw_parts(ptr, len as usize);
+ let mut image = image::RgbImage::new(w, h);
+ for y in 0..h as usize {
+ let row = if stride < 0 { h as usize - 1 - y } else { y };
+ for x in 0..w as usize {
+ let p = row * pitch + x * 4;
+ image.put_pixel(
+ x as u32,
+ y as u32,
+ image::Rgb([bytes[p + 2], bytes[p + 1], bytes[p]]),
+ );
+ }
+ }
+ let data = crate::content::jpeg(
+ &image::DynamicImage::ImageRgb8(image),
+ 1024.min(w.max(h)),
+ )?;
+ return Ok(Some((stamp as f32 / 10_000_000.0, data)));
+ }
+ anyhow::bail!("Native video seek limit reached")
+ }
+ }
+ }
+}
+#[cfg(windows)]
+pub use win::{Reader, adapters};
+#[cfg(not(windows))]
+pub fn adapters() -> Vec<(String, String)> {
+ vec![]
+}
+#[cfg(not(windows))]
+pub struct Reader;
+#[cfg(not(windows))]
+impl Reader {
+ pub fn open(_: &Path, _: &Settings) -> Result<Self> {
+ anyhow::bail!("Windows video decoder is unavailable on this platform")
+ }
+ pub fn duration(&self) -> Option<f32> {
+ None
+ }
+ pub fn has_audio(&self) -> bool {
+ false
+ }
+ pub fn frame(&self, _: f32, _: &dyn Fn() -> Result<()>) -> Result<Option<(f32, Vec<u8>)>> {
+ anyhow::bail!("Windows video decoder is unavailable")
+ }
+}
+pub fn open(path: &Path, s: &Settings) -> Result<Reader> {
+ match Reader::open(path, s) {
+ Ok(r) => Ok(r),
+ Err(_) if s.video_decode_device == "Auto" && gpu_requested(s) => {
+ let mut cpu = s.clone();
+ cpu.video_decode_device = "CPU".into();
+ Reader::open(path, &cpu)
+ }
+ Err(e) => Err(e),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn decoder_device_is_separate_from_embedding_device() {
+ let mut s = Settings::default();
+ s.hardware = "CPU / system RAM".into();
+ assert!(!gpu_requested(&s));
+ s.video_decode_device = "GPU".into();
+ assert!(gpu_requested(&s));
+ s.hardware = "Dedicated GPU".into();
+ s.video_decode_device = "CPU".into();
+ assert!(!gpu_requested(&s));
+ s.video_decode_device = "Auto".into();
+ assert!(gpu_requested(&s));
+ }
+ #[cfg(windows)]
+ #[test]
+ #[ignore = "Requires Windows Media Foundation H.264 decoder"]
+ fn native_cpu_decodes_seeks_and_releases_without_ffmpeg() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("colors.mp4");
+ std::fs::write(&path, include_bytes!("../tests/fixtures/video-colors.mp4")).unwrap();
+ let s = Settings {
+ video_decode_device: "CPU".into(),
+ ..Default::default()
+ };
+ let reader = open(&path, &s).unwrap();
+ assert!(!reader.has_audio());
+ assert!(reader.duration().unwrap() > 1.9);
+ for time in [0.0, 1.0] {
+ let (stamp, jpeg) = reader.frame(time, &|| Ok(())).unwrap().unwrap();
+ assert!(stamp >= time && stamp < time + 0.6);
+ let image = image::load_from_memory(&jpeg).unwrap().to_rgb8();
+ let top = image.get_pixel(image.width() / 2, image.height() / 4);
+ let bottom = image.get_pixel(image.width() / 2, image.height() * 3 / 4);
+ assert!(
+ top[0] > 200 && top[2] < 40,
+ "RGB channel order/top orientation"
+ );
+ assert!(bottom[2] > 200 && bottom[0] < 40, "bottom orientation");
+ }
+ assert!(
+ reader
+ .frame(0.0, &|| anyhow::bail!("cancelled"))
+ .unwrap_err()
+ .to_string()
+ .contains("cancelled")
+ );
+ drop(reader);
+ std::fs::remove_file(path).unwrap();
+ }
+}
diff --git a/native/tests/fixtures/video-colors.mp4 b/native/tests/fixtures/video-colors.mp4
new file mode 100644
index 0000000..3aaa597
Binary files /dev/null and b/native/tests/fixtures/video-colors.mp4 differ