Skip to main content

adk_vision/sam/
decode.rs

1//! Turning `sam-3.1` mask payloads into rasters: the decoder trait, a user-installed
2//! program, and, with feature `sam-codec`, the licensed port of Meta's codec.
3
4use 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/// Decodes `sam-3.1` mask payloads into row-major rasters of `height × width` bits.
19///
20/// Meta's payload is base85 text around an arithmetic-coded body whose model is defined
21/// only by Meta's own parser, `@meta-sam/parser`, published under the SAM License. The
22/// Apache-2.0 crates hold no SAM-licensed code: a [`SamSegmenter`](super::SamSegmenter)
23/// without a decoder answers with each object's box in source pixels; with one, with its
24/// mask. [`MaskDecoderChoice`] picks [`ExternalMaskDecoder`] or, with feature `sam-codec`,
25/// `LicensedMaskDecoder`; any other implementation is installed with
26/// [`SamSegmenter::with_mask_decoder`](super::SamSegmenter::with_mask_decoder).
27///
28/// # Example
29///
30/// ```
31/// use adk_vision::sam::{SamMask, SamMaskDecoder};
32///
33/// /// Every mask is solid: its box is the object.
34/// struct Solid;
35///
36/// #[async_trait::async_trait]
37/// impl SamMaskDecoder for Solid {
38///     async fn decode(&self, masks: &[SamMask]) -> adk_vision::Result<Vec<Vec<bool>>> {
39///         Ok(masks.iter().map(|m| vec![true; (m.width * m.height) as usize]).collect())
40///     }
41/// }
42/// ```
43#[async_trait]
44pub trait SamMaskDecoder: Send + Sync {
45    /// One row-major raster of `height × width` bits per mask, in order.
46    ///
47    /// # Errors
48    ///
49    /// The decoder's failure; the segmenter refuses the answer rather than guess.
50    async fn decode(&self, masks: &[SamMask]) -> Result<Vec<Vec<bool>>>;
51}
52
53/// The backend name decoder errors carry.
54const DECODER: &str = "sam-3.1 mask decoder";
55/// The most standard error kept from a failing program.
56const MAX_STDERR: u64 = 64 * 1024;
57
58fn decoder_error(message: String) -> VisionError {
59    VisionError::Backend { backend: DECODER.into(), message }
60}
61
62/// Decodes masks with a program the user installed, the way the video backends use a
63/// user-installed `ffmpeg`: this crate neither bundles nor downloads it.
64///
65/// The program is started once per answer with its arguments. It reads a JSON array of
66/// `{"encoding", "width", "height", "payload"}` on standard input (`encoding` is `lossless`
67/// or `one_bit`, `payload` the mask text exactly as the API sent it) and writes a JSON array
68/// with one base64 string per mask: `height × width` bytes, row-major, nonzero for a set
69/// pixel. A missing program, a non-zero exit, output that is not that array, and a decode
70/// that outlasts the timeout are each an error naming what went wrong; the program is
71/// killed when the timeout ends it.
72///
73/// [`ExternalMaskDecoder::meta_parser`] runs Meta's `@meta-sam/parser` in a user-installed
74/// Node.js; installing that package (`npm install @meta-sam/parser`) accepts its licence.
75///
76/// # Example
77///
78/// ```no_run
79/// use std::time::Duration;
80/// use adk_vision::sam::ExternalMaskDecoder;
81/// use adk_vision::{MaskDecoderChoice, SamConfig, SamSegmenter};
82///
83/// // Through the configuration, as `.adk/vision.toml` would choose it.
84/// let sam = SamSegmenter::new(
85///     SamConfig::new("meta-key")
86///         .with_mask_decoder(MaskDecoderChoice::external("sam-mask-decode", ["--json"])),
87/// )?;
88///
89/// // Or directly, here Meta's parser in Node.js.
90/// let decoder = ExternalMaskDecoder::meta_parser("/opt/sam/node_modules/@meta-sam/parser")
91///     .with_timeout(Duration::from_secs(20));
92/// # Ok::<(), adk_vision::VisionError>(())
93/// ```
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct ExternalMaskDecoder {
96    program: PathBuf,
97    args: Vec<String>,
98    timeout: Duration,
99}
100
101/// Reads `[{encoding, width, height, payload}]` from standard input and writes one base64
102/// raster per mask; the package path is the last argument.
103const 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    /// A decoder running `program` (a path, or a name looked up on `PATH`) with no
117    /// arguments and a 60-second timeout.
118    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    /// Meta's `@meta-sam/parser` at `package` (the directory holding its `package.json`),
127    /// run by `node` from `PATH`; [`with_program`](Self::with_program) names another
128    /// `node`.
129    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    /// Runs this program instead.
140    pub fn with_program(mut self, program: impl Into<PathBuf>) -> Self {
141        self.program = program.into();
142        self
143    }
144
145    /// Passes these arguments, replacing any set before.
146    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    /// Ends a decode that takes longer than `timeout`.
152    pub fn with_timeout(mut self, timeout: Duration) -> Self {
153        self.timeout = timeout;
154        self
155    }
156
157    /// The program this decoder runs.
158    pub fn program(&self) -> &Path {
159        &self.program
160    }
161
162    /// Checks that the program exists: a path names a file, a bare name is on `PATH`.
163    ///
164    /// # Errors
165    ///
166    /// [`VisionError::InvalidInput`] naming the program and how to fix the configuration.
167    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
180/// The file `program` names: itself when it has a directory part, else the first match on
181/// `PATH` (with Windows' executable extensions).
182fn 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                    // The wire text: Meta's decoders read the marker as part of the payload.
221                    "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        // Base64 of every raster plus the JSON around it; more is not an answer.
227        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        // Standard error drains on its own, so a program stopped for writing too much still
247        // closes it.
248        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            // A program that exits without reading its input closes the pipe; its exit
255            // status and output say why.
256            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            // A child the program left behind may hold standard error open; wait briefly.
290            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/// Decodes masks in this process with `adk-vision-sam-codec`, the Rust port of the mask
336/// codec in Meta's `@meta-sam/parser`, distributed under the SAM License.
337///
338/// Constructing one checks the licence gate: a person must have accepted the SAM License
339/// for the [`SAM_MASK_CODEC_MANIFEST`](crate::SAM_MASK_CODEC_MANIFEST) entry
340/// (`adk-rust vision models accept sam-mask-codec`). Each raster is bounded before it is
341/// allocated, by default to 50 million pixels.
342///
343/// # Example
344///
345/// ```
346/// use adk_vision::sam::LicensedMaskDecoder;
347/// use adk_vision::{
348///     AcceptanceStore, InMemoryAcceptanceStore, LicenceAcceptance, ManifestSet,
349///     SAM_MASK_CODEC_MANIFEST,
350/// };
351///
352/// let store = InMemoryAcceptanceStore::new();
353/// let refused = LicensedMaskDecoder::new(&store).unwrap_err().to_string();
354/// assert!(refused.contains("licence acceptance required"));
355/// assert!(refused.contains("github.com/meta-models/meta-sam"));
356///
357/// let manifests = ManifestSet::builtin().unwrap();
358/// let codec = manifests.get(SAM_MASK_CODEC_MANIFEST).unwrap();
359/// store.record(LicenceAcceptance::of(codec, "alice@example.com")).unwrap();
360/// assert!(LicensedMaskDecoder::new(&store).is_ok());
361/// ```
362#[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    /// The decoder, once the licence gate allows the codec.
371    ///
372    /// # Errors
373    ///
374    /// [`VisionError::LicenceAcceptanceRequired`] naming the licence URL until a person has
375    /// accepted it, or the acceptance store's error.
376    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    /// Refuses any raster larger than `pixels` before allocating it.
388    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        // A large raster is milliseconds of arithmetic decoding; keep it off the runtime.
405        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
431/// The decoder a configuration chooses, checked now rather than at the first answer.
432pub(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}