1use std::path::{Path, PathBuf};
5use std::process::Stdio;
6use std::sync::Arc;
7use std::time::Duration;
8
9use async_trait::async_trait;
10use base64::Engine as _;
11use tokio::io::{AsyncReadExt, AsyncWriteExt};
12
13use super::parse::SamMask;
14use crate::error::{Result, VisionError};
15use crate::manifest::AcceptanceStore;
16use crate::mask_decoder::MaskDecoderChoice;
17
18#[async_trait]
44pub trait SamMaskDecoder: Send + Sync {
45 async fn decode(&self, masks: &[SamMask]) -> Result<Vec<Vec<bool>>>;
51}
52
53const DECODER: &str = "sam-3.1 mask decoder";
55const MAX_STDERR: u64 = 64 * 1024;
57
58fn decoder_error(message: String) -> VisionError {
59 VisionError::Backend { backend: DECODER.into(), message }
60}
61
62#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct ExternalMaskDecoder {
96 program: PathBuf,
97 args: Vec<String>,
98 timeout: Duration,
99}
100
101const META_PARSER_SCRIPT: &str = r#"
104import { pathToFileURL } from 'node:url';
105import { join } from 'node:path';
106const pkg = process.argv[process.argv.length - 1];
107const { decodeMaskToRaster } = await import(pathToFileURL(join(pkg, 'dist', 'index.js')).href);
108let input = '';
109for await (const chunk of process.stdin) input += chunk;
110const masks = JSON.parse(input);
111const out = masks.map((m) => Buffer.from(decodeMaskToRaster(m)).toString('base64'));
112process.stdout.write(JSON.stringify(out));
113"#;
114
115impl ExternalMaskDecoder {
116 pub fn new(program: impl Into<PathBuf>) -> Self {
119 Self {
120 program: program.into(),
121 args: Vec::new(),
122 timeout: Duration::from_secs(crate::mask_decoder::DEFAULT_MASK_DECODER_TIMEOUT_SECS),
123 }
124 }
125
126 pub fn meta_parser(package: impl Into<PathBuf>) -> Self {
130 let package: PathBuf = package.into();
131 Self::new("node").with_args([
132 "--input-type=module".to_string(),
133 "-e".to_string(),
134 META_PARSER_SCRIPT.to_string(),
135 package.to_string_lossy().into_owned(),
136 ])
137 }
138
139 pub fn with_program(mut self, program: impl Into<PathBuf>) -> Self {
141 self.program = program.into();
142 self
143 }
144
145 pub fn with_args<A: Into<String>>(mut self, args: impl IntoIterator<Item = A>) -> Self {
147 self.args = args.into_iter().map(Into::into).collect();
148 self
149 }
150
151 pub fn with_timeout(mut self, timeout: Duration) -> Self {
153 self.timeout = timeout;
154 self
155 }
156
157 pub fn program(&self) -> &Path {
159 &self.program
160 }
161
162 pub fn check(&self) -> Result<()> {
168 if resolve(&self.program).is_some() {
169 return Ok(());
170 }
171 Err(VisionError::InvalidInput(format!(
172 "the sam-3.1 mask decoder program `{}` was not found{}; install it, give its full \
173 path, or choose `decoder = \"boxes\"` to answer with boxes",
174 self.program.display(),
175 if self.program.components().count() > 1 { "" } else { " on PATH" },
176 )))
177 }
178}
179
180fn resolve(program: &Path) -> Option<PathBuf> {
183 if program.components().count() > 1 || program.is_absolute() {
184 return program.is_file().then(|| program.to_path_buf());
185 }
186 let extensions: Vec<String> = if cfg!(windows) {
187 std::env::var("PATHEXT")
188 .unwrap_or_else(|_| ".EXE;.CMD;.BAT;.COM".into())
189 .split(';')
190 .map(str::to_string)
191 .chain([String::new()])
192 .collect()
193 } else {
194 vec![String::new()]
195 };
196 std::env::split_paths(&std::env::var_os("PATH")?).find_map(|dir| {
197 extensions.iter().find_map(|ext| {
198 let mut name = program.as_os_str().to_os_string();
199 name.push(ext);
200 let candidate = dir.join(name);
201 candidate.is_file().then_some(candidate)
202 })
203 })
204}
205
206#[async_trait]
207impl SamMaskDecoder for ExternalMaskDecoder {
208 async fn decode(&self, masks: &[SamMask]) -> Result<Vec<Vec<bool>>> {
209 if masks.is_empty() {
210 return Ok(Vec::new());
211 }
212 let program = self.program.display().to_string();
213 let input: Vec<serde_json::Value> = masks
214 .iter()
215 .map(|m| {
216 serde_json::json!({
217 "encoding": m.encoding,
218 "width": m.width,
219 "height": m.height,
220 "payload": format!("{}{}", m.encoding.marker(), m.payload),
222 })
223 })
224 .collect();
225 let input = serde_json::to_vec(&input).map_err(|e| decoder_error(e.to_string()))?;
226 let area: u64 = masks.iter().map(|m| u64::from(m.width) * u64::from(m.height)).sum();
228 let max_stdout = area.saturating_mul(4) / 3 + 8 * masks.len() as u64 + 1024;
229 let mut child = tokio::process::Command::new(&self.program)
230 .args(&self.args)
231 .stdin(Stdio::piped())
232 .stdout(Stdio::piped())
233 .stderr(Stdio::piped())
234 .kill_on_drop(true)
235 .spawn()
236 .map_err(|e| match e.kind() {
237 std::io::ErrorKind::NotFound => decoder_error(format!(
238 "the program `{program}` was not found; install it, give its full path, or \
239 choose `decoder = \"boxes\"`"
240 )),
241 _ => decoder_error(format!("could not start `{program}`: {e}")),
242 })?;
243 let mut stdin = child.stdin.take().ok_or_else(|| decoder_error("no stdin".into()))?;
244 let stdout = child.stdout.take().ok_or_else(|| decoder_error("no stdout".into()))?;
245 let stderr = child.stderr.take().ok_or_else(|| decoder_error("no stderr".into()))?;
246 let errors = tokio::spawn(async move {
249 let mut err = Vec::new();
250 let _ = stderr.take(MAX_STDERR).read_to_end(&mut err).await;
251 err
252 });
253 let work = async {
254 let written = async {
257 let _ = stdin.write_all(&input).await;
258 drop(stdin);
259 };
260 let mut out = Vec::new();
261 let mut stdout = stdout.take(max_stdout + 1);
262 let (_, read) = tokio::join!(written, stdout.read_to_end(&mut out));
263 read?;
264 if out.len() as u64 > max_stdout {
265 child.start_kill()?;
266 child.wait().await?;
267 return Ok((None, out));
268 }
269 Ok::<_, std::io::Error>((Some(child.wait().await?), out))
270 };
271 let (status, out) = tokio::time::timeout(self.timeout, work)
272 .await
273 .map_err(|_| {
274 decoder_error(format!(
275 "`{program}` took longer than {:?} and was stopped; raise `timeout_secs` or \
276 check the program",
277 self.timeout
278 ))
279 })?
280 .map_err(|e| decoder_error(format!("`{program}`: {e}")))?;
281 let Some(status) = status else {
282 return Err(decoder_error(format!(
283 "`{program}` wrote more than {max_stdout} bytes for {} masks and was stopped; it \
284 must write one JSON array of base64 rasters",
285 masks.len()
286 )));
287 };
288 if !status.success() {
289 let err = tokio::time::timeout(Duration::from_secs(1), errors)
291 .await
292 .ok()
293 .and_then(std::result::Result::ok)
294 .unwrap_or_default();
295 let err = String::from_utf8_lossy(&err);
296 let first = err.lines().find(|l| !l.trim().is_empty()).unwrap_or_default();
297 return Err(decoder_error(format!("`{program}` exited with {status}: {first}")));
298 }
299 errors.abort();
300 let rasters: Vec<String> = serde_json::from_slice(&out).map_err(|e| {
301 decoder_error(format!(
302 "`{program}` answered unreadable output ({e}); it must write one JSON array of \
303 base64 rasters"
304 ))
305 })?;
306 if rasters.len() != masks.len() {
307 return Err(decoder_error(format!(
308 "`{program}` answered {} rasters for {} masks",
309 rasters.len(),
310 masks.len()
311 )));
312 }
313 rasters
314 .iter()
315 .zip(masks)
316 .enumerate()
317 .map(|(i, (b64, mask))| {
318 let bytes = base64::engine::general_purpose::STANDARD.decode(b64).map_err(|e| {
319 decoder_error(format!("`{program}` raster {i} is not base64: {e}"))
320 })?;
321 if bytes.len() as u64 != u64::from(mask.width) * u64::from(mask.height) {
322 return Err(decoder_error(format!(
323 "`{program}` raster {i} has {} bytes for a {}x{} mask",
324 bytes.len(),
325 mask.width,
326 mask.height
327 )));
328 }
329 Ok(bytes.into_iter().map(|b| b != 0).collect())
330 })
331 .collect()
332 }
333}
334
335#[cfg(feature = "sam-codec")]
363#[derive(Clone, Debug)]
364pub struct LicensedMaskDecoder {
365 max_area: usize,
366}
367
368#[cfg(feature = "sam-codec")]
369impl LicensedMaskDecoder {
370 pub fn new(acceptances: &dyn AcceptanceStore) -> Result<Self> {
377 let manifests = crate::manifest::ManifestSet::builtin()?;
378 let manifest =
379 manifests.get(crate::mask_decoder::SAM_MASK_CODEC_MANIFEST).ok_or_else(|| {
380 VisionError::BackendNotFound("the built-in manifest has no sam-mask-codec".into())
381 })?;
382 let policy = crate::manifest::LicencePolicy::new();
383 crate::manifest::LicenceGate::new(&policy, acceptances).check(manifest)?;
384 Ok(Self { max_area: 50_000_000 })
385 }
386
387 pub fn with_max_area(mut self, pixels: usize) -> Self {
389 self.max_area = pixels;
390 self
391 }
392}
393
394#[cfg(feature = "sam-codec")]
395#[async_trait]
396impl SamMaskDecoder for LicensedMaskDecoder {
397 async fn decode(&self, masks: &[SamMask]) -> Result<Vec<Vec<bool>>> {
398 use adk_vision_sam_codec::{EncodedMask, Encoding, decode_mask_to_raster};
399
400 use super::parse::SamMaskEncoding;
401
402 let masks = masks.to_vec();
403 let max_area = self.max_area;
404 tokio::task::spawn_blocking(move || {
406 masks
407 .iter()
408 .enumerate()
409 .map(|(i, m)| {
410 let encoding = match m.encoding {
411 SamMaskEncoding::Lossless => Encoding::Lossless,
412 SamMaskEncoding::OneBit => Encoding::OneBit,
413 };
414 let text = format!("{}{}", m.encoding.marker(), m.payload);
415 let mask =
416 EncodedMask { encoding, width: m.width, height: m.height, payload: &text };
417 decode_mask_to_raster(&mask, max_area)
418 .map(|raster| raster.into_iter().map(|b| b == 1).collect())
419 .map_err(|e| VisionError::Parse {
420 backend: DECODER.into(),
421 message: format!("mask {i}: {e}"),
422 })
423 })
424 .collect()
425 })
426 .await
427 .map_err(|e| decoder_error(e.to_string()))?
428 }
429}
430
431pub(crate) fn decoder_for(
433 choice: &MaskDecoderChoice,
434 acceptances: Option<&dyn AcceptanceStore>,
435) -> Result<Option<Arc<dyn SamMaskDecoder>>> {
436 match choice {
437 MaskDecoderChoice::None => Ok(None),
438 MaskDecoderChoice::External { program, args, timeout_secs } => {
439 let decoder = ExternalMaskDecoder::new(program.clone())
440 .with_args(args.iter().cloned())
441 .with_timeout(Duration::from_secs(*timeout_secs));
442 decoder.check()?;
443 Ok(Some(Arc::new(decoder)))
444 }
445 #[cfg(feature = "sam-codec")]
446 MaskDecoderChoice::Licensed => {
447 let empty = crate::manifest::InMemoryAcceptanceStore::new();
448 let decoder = LicensedMaskDecoder::new(acceptances.unwrap_or(&empty))?;
449 Ok(Some(Arc::new(decoder)))
450 }
451 #[cfg(not(feature = "sam-codec"))]
452 MaskDecoderChoice::Licensed => {
453 let _ = acceptances;
454 Err(VisionError::Unsupported(
455 "`decoder = \"licensed\"` needs adk-vision's `sam-codec` feature (adk-rust: \
456 `vision-sam-codec`), which this build lacks; rebuild with it, or choose \
457 `external` or `boxes`"
458 .into(),
459 ))
460 }
461 }
462}