Skip to main content

adk_vision/sam/
video.rs

1//! [`SamVideoTracker`]: `sam-3.1` video, masks with stable object identifiers over a clip
2//! (spec 3.7 §7.7, §7.13), for an ambiguous track's escalation.
3
4use std::collections::{BTreeMap, HashMap};
5use std::sync::Arc;
6
7use adk_core::UsageUnit;
8use adk_model::pricing::PricingCatalog;
9use async_trait::async_trait;
10use base64::Engine as _;
11use serde_json::{Value, json};
12use tokio::sync::Mutex;
13
14use super::{
15    Answer, Job, SamConfig, SamMask, SamMaskDecoder, SamSegmenter, VENDOR, object_prompt, place,
16    redact, status_error,
17};
18use crate::backend::{BackendDescriptor, PriceRef};
19use crate::cx::VisionCx;
20use crate::digest::Digest;
21use crate::egress::{ReleasedClip, ReleasedImage};
22use crate::error::{Result, VisionError};
23use crate::geometry::{BBox, CoordFrame, RawRegion, Shape, TrackId};
24use crate::traits::{
25    SegmentPrompt, VideoAnalysis, VideoAnalyzer, VideoFrame, VideoInput, VideoRequest, VideoUsage,
26};
27
28/// Which frames `sam-3.1` tracks from a prompt: `metadata.propagation_direction`.
29#[non_exhaustive]
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub enum Propagation {
32    /// Before and after the earliest prompted frame (the API's default).
33    #[default]
34    Both,
35    /// From the earliest prompted frame to the end of the clip.
36    Forward,
37    /// From the earliest prompted frame back to the start.
38    Backward,
39}
40
41/// The most a request carries inline before the clip is uploaded through `/v1/files`.
42pub const SAM_VIDEO_INLINE_LIMIT: usize = 20 * 1024 * 1024;
43
44/// Meta's `sam-3.1` over a video clip, as a remote [`VideoAnalyzer`] answering `Track`.
45///
46/// Each concept phrase is one `POST /v1/responses` request with the released clip as an
47/// `input_video` part — a data URL up to [`inline_limit`](Self::with_inline_limit), else a
48/// `file_id` uploaded once through `/v1/files` — streamed through `response.completed`. Box
49/// and point prompts go in one request on frame 0. The answer is one line per frame with
50/// objects; each object becomes a region with a [`TrackId`] that is stable across the
51/// frames of the analysis (objects of different concepts never share one), a mask when a
52/// [`SamMaskDecoder`] is installed and its box otherwise, in pixels of the clip's frames.
53///
54/// | Item | Behaviour |
55/// |------|-----------|
56/// | Price | $0.20 per 1,000 frames, at least 50 frames per request, from the `adk-model` catalog; a three-concept query is three requests over every frame |
57/// | Limits | Up to 15,000 frames (about 10 minutes) and 16 objects per frame per request; MP4 or MOV with H.264, H.265 or MPEG-4 |
58/// | Credentials | As [`SamSegmenter`]: the Meta Model API key and Muse's base URL |
59///
60/// # Example
61///
62/// ```
63/// use adk_vision::sam::{SamConfig, SamVideoTracker};
64/// use adk_vision::{ReleasedImage, VideoAnalyzer};
65///
66/// let sam = SamVideoTracker::new(SamConfig::new("meta-key")).unwrap();
67/// let price = VideoAnalyzer::<ReleasedImage>::descriptor(&sam).price.clone().unwrap();
68/// // Twelve frames bill the 50-frame minimum; 900 frames are 900.
69/// assert_eq!(price.request_cost(12), Some(10_000));
70/// assert_eq!(price.request_cost(900), Some(180_000));
71/// ```
72pub struct SamVideoTracker {
73    inner: SamSegmenter,
74    descriptor: BackendDescriptor,
75    propagation: Propagation,
76    inline_limit: usize,
77    uploads: Mutex<HashMap<Digest, String>>,
78}
79
80impl std::fmt::Debug for SamVideoTracker {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        f.debug_struct("SamVideoTracker")
83            .field("inner", &self.inner)
84            .field("descriptor", &self.descriptor)
85            .field("propagation", &self.propagation)
86            .field("inline_limit", &self.inline_limit)
87            .finish_non_exhaustive()
88    }
89}
90
91impl SamVideoTracker {
92    /// A client for `config`.
93    ///
94    /// # Errors
95    ///
96    /// As [`SamSegmenter::new`], and [`VisionError::InvalidInput`] when the catalog has no
97    /// frame price for the model.
98    pub fn new(config: SamConfig) -> Result<Self> {
99        let model = config.model.clone();
100        let inner = SamSegmenter::new(config)?;
101        let rate = PricingCatalog::standard()
102            .unit_price(Some(VENDOR), &model, UsageUnit::Frames)
103            .map(|p| p.rate)
104            .ok_or_else(|| {
105                VisionError::InvalidInput(format!(
106                    "the pricing catalog has no frame price for `{model}`"
107                ))
108            })?;
109        let descriptor = BackendDescriptor::new(
110            model.clone(),
111            inner.descriptor.locality.clone(),
112            CoordFrame::SentPixels,
113        )
114        .with_price(PriceRef::PerUnit {
115            vendor: VENDOR.into(),
116            model,
117            rate,
118            min_units_per_request: rate.minimum_per_request,
119        })
120        .with_concepts_per_request(1);
121        Ok(Self {
122            inner,
123            descriptor,
124            propagation: Propagation::Both,
125            inline_limit: SAM_VIDEO_INLINE_LIMIT,
126            uploads: Mutex::new(HashMap::new()),
127        })
128    }
129
130    /// Answers with masks, decoded by `decoder`.
131    pub fn with_mask_decoder(mut self, decoder: Arc<dyn SamMaskDecoder>) -> Self {
132        self.inner = self.inner.with_mask_decoder(decoder);
133        self
134    }
135
136    /// Names the hosts the egress policy checks instead of the base URL's.
137    pub fn with_hosts<H: Into<String>>(mut self, hosts: impl IntoIterator<Item = H>) -> Self {
138        let hosts: Vec<String> = hosts.into_iter().map(Into::into).collect();
139        self.inner = self.inner.with_hosts(hosts.clone());
140        self.descriptor.locality = crate::backend::Locality::Remote { hosts };
141        self
142    }
143
144    /// Tracks in `direction` from the earliest prompted frame.
145    pub fn with_propagation(mut self, direction: Propagation) -> Self {
146        self.propagation = direction;
147        self
148    }
149
150    /// Sends clips up to `bytes` inline and uploads larger ones; 0 always uploads.
151    pub fn with_inline_limit(mut self, bytes: usize) -> Self {
152        self.inline_limit = bytes;
153        self
154    }
155
156    /// The `input_video` part: a data URL, or a file uploaded once.
157    async fn media(&self, cx: &VisionCx, clip: &ReleasedClip) -> Result<Value> {
158        if clip.bytes().len() <= self.inline_limit {
159            let data = base64::engine::general_purpose::STANDARD.encode(clip.bytes());
160            return Ok(json!({
161                "type": "input_video",
162                "video_url": format!("data:{};base64,{data}", clip.mime_type())
163            }));
164        }
165        let digest = clip.receipt().egress;
166        let mut uploads = self.uploads.lock().await;
167        if let Some(id) = uploads.get(&digest) {
168            return Ok(json!({"type": "input_video", "file_id": id}));
169        }
170        cx.check()?;
171        let backend = self.descriptor.id.to_string();
172        let extension = if clip.mime_type() == "video/quicktime" { "mov" } else { "mp4" };
173        let file = reqwest::multipart::Part::bytes(clip.bytes().to_vec())
174            .file_name(format!("clip.{extension}"))
175            .mime_str(clip.mime_type())
176            .map_err(|e| VisionError::InvalidInput(e.to_string()))?;
177        let form = reqwest::multipart::Form::new().text("purpose", "user_data").part("file", file);
178        let response = self
179            .inner
180            .http
181            .post(format!("{}/files", self.inner.config.base_url))
182            .bearer_auth(&self.inner.config.api_key)
183            .multipart(form)
184            .send()
185            .await
186            .map_err(|e| VisionError::Unavailable {
187                backend: backend.clone(),
188                message: redact(&e.to_string()),
189            })?;
190        let status = response.status();
191        let text = response.text().await.unwrap_or_default();
192        if !status.is_success() {
193            return Err(status_error(&backend, status.as_u16(), &text));
194        }
195        let id = serde_json::from_str::<Value>(&text)
196            .ok()
197            .and_then(|v| v.get("id").and_then(Value::as_str).map(str::to_string))
198            .ok_or_else(|| VisionError::Parse {
199                backend: backend.clone(),
200                message: format!("the upload answer names no file id: {}", redact(&text)),
201            })?;
202        tracing::info!(vision.backend = %backend, sam.file = %id, clip.bytes = clip.bytes().len(), "clip uploaded for sam-3.1");
203        uploads.insert(digest, id.clone());
204        Ok(json!({"type": "input_video", "file_id": id}))
205    }
206
207    /// The request body for one text part and the clip's part.
208    pub(crate) fn body(&self, text: &str, media: &Value) -> Value {
209        let mut body = json!({
210            "model": self.inner.config.model,
211            "stream": true,
212            "input": [{
213                "type": "message",
214                "role": "user",
215                "content": [{"type": "input_text", "text": text}, media]
216            }]
217        });
218        let mut metadata = serde_json::Map::new();
219        if self.inner.config.include_confidence {
220            metadata.insert("include_confidence".into(), json!("true"));
221        }
222        if self.inner.config.one_bit {
223            metadata.insert("mask_encoding".into(), json!("one_bit"));
224        }
225        match self.propagation {
226            Propagation::Both => {}
227            Propagation::Forward => {
228                metadata.insert("propagation_direction".into(), json!("forward"));
229            }
230            Propagation::Backward => {
231                metadata.insert("propagation_direction".into(), json!("backward"));
232            }
233        }
234        if !metadata.is_empty() {
235            body["metadata"] = Value::Object(metadata);
236        }
237        body
238    }
239
240    /// One answer's records as regions by frame, objects numbered from `base`; returns the
241    /// next free identifier.
242    async fn collect(
243        &self,
244        answer: Answer,
245        label: Option<String>,
246        size: (u32, u32),
247        base: u64,
248        frames: &mut BTreeMap<u64, Vec<RawRegion>>,
249    ) -> Result<u64> {
250        let parse = |message: String| VisionError::Parse {
251            backend: self.descriptor.id.to_string(),
252            message,
253        };
254        for r in &answer.records {
255            if r.source != size {
256                return Err(parse(format!(
257                    "a record is in a {}x{} frame, but the clip's frames are {}x{}",
258                    r.source.0, r.source.1, size.0, size.1
259                )));
260            }
261        }
262        let rasters = match &self.inner.decoder {
263            Some(decoder) => {
264                let masks: Vec<SamMask> = answer.records.iter().map(|r| r.mask.clone()).collect();
265                let rasters = decoder.decode(&masks).await?;
266                if rasters.len() != masks.len() {
267                    return Err(parse(format!(
268                        "{} rasters for {} masks",
269                        rasters.len(),
270                        masks.len()
271                    )));
272                }
273                Some(rasters)
274            }
275            None => None,
276        };
277        let mut next = base;
278        for (i, record) in answer.records.iter().enumerate() {
279            let object: u64 = record
280                .object
281                .parse()
282                .map_err(|_| parse(format!("object id `{}` is not a number", record.object)))?;
283            let id =
284                base.checked_add(object).ok_or_else(|| parse("an object id overflows".into()))?;
285            next = next.max(id + 1);
286            let [x0, y0, x1, y1] = record.bounds;
287            let shape = match rasters.as_ref().map(|r| &r[i]) {
288                Some(bits) => Shape::Mask(place(bits, record, size).map_err(parse)?),
289                None => Shape::Box(BBox::new(x0 as f32, y0 as f32, x1 as f32, y1 as f32)),
290            };
291            frames.entry(record.frame).or_default().push(RawRegion {
292                shape,
293                label: label.clone().or_else(|| Some(format!("object {object}"))),
294                score: record.confidence,
295                track: Some(TrackId(id)),
296            });
297        }
298        Ok(next)
299    }
300}
301
302#[async_trait]
303impl VideoAnalyzer<ReleasedImage> for SamVideoTracker {
304    fn descriptor(&self) -> &BackendDescriptor {
305        &self.descriptor
306    }
307
308    async fn analyze(
309        &self,
310        cx: &VisionCx,
311        video: &VideoInput<ReleasedImage>,
312        request: &VideoRequest,
313    ) -> Result<VideoAnalysis<RawRegion>> {
314        let VideoRequest::Track { prompts } = request else {
315            return Err(VisionError::Unsupported(format!(
316                "`{}` video answers `Track`; ask questions with a `FramesAnalyzer` or Gemini",
317                self.descriptor.id
318            )));
319        };
320        let Some(clip) = video.clip.as_ref() else {
321            return Err(VisionError::Unsupported(format!(
322                "`{}` video reads a clip; segment sampled frames with `SamSegmenter`",
323                self.descriptor.id
324            )));
325        };
326        if !clip.is_for(&self.descriptor.id) {
327            return Err(VisionError::NotReleased {
328                backend: format!(
329                    "{} (the clip was released to `{}`)",
330                    self.descriptor.id,
331                    clip.receipt().backend
332                ),
333            });
334        }
335        let size = clip.clip().size();
336        let mut jobs = Vec::new();
337        let mut objects = Vec::new();
338        for prompt in prompts {
339            match prompt {
340                SegmentPrompt::Concept { text } => {
341                    jobs.push(Job { text: text.clone(), label: Some(text.clone()) });
342                }
343                other => objects.push(other),
344            }
345        }
346        if !objects.is_empty() {
347            jobs.push(Job { text: object_prompt(&objects, size)?, label: None });
348        }
349        if jobs.is_empty() {
350            return Err(VisionError::InvalidInput("track needs at least one prompt".into()));
351        }
352        let media = self.media(cx, clip).await?;
353        let mut frames = BTreeMap::new();
354        let mut base = 0u64;
355        let requests = jobs.len() as u64;
356        for job in jobs {
357            cx.check()?;
358            let answer = self.inner.send(cx, &self.body(&job.text, &media)).await?;
359            base = self.collect(answer, job.label, size, base, &mut frames).await?;
360        }
361        let info = clip.info();
362        let pts = |frame: u64| {
363            (info.frames > 0).then(|| {
364                u64::try_from(
365                    u128::from(frame) * u128::from(info.duration_ms) / u128::from(info.frames),
366                )
367                .unwrap_or(u64::MAX)
368            })
369        };
370        Ok(VideoAnalysis {
371            frames: frames
372                .into_iter()
373                .map(|(index, regions)| VideoFrame { index, pts_ms: pts(index), regions })
374                .collect(),
375            usage: VideoUsage { requests, ..VideoUsage::default() },
376            ..VideoAnalysis::default()
377        })
378    }
379}
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384
385    #[test]
386    fn video_requests_carry_the_clip_and_the_propagation() {
387        let sam = SamVideoTracker::new(SamConfig::new("k").with_one_bit_masks(true))
388            .unwrap()
389            .with_propagation(Propagation::Forward);
390        let media = json!({"type": "input_video", "file_id": "file-1"});
391        let body = sam.body("forklift", &media);
392        assert_eq!(
393            body,
394            json!({
395                "model": "sam-3.1",
396                "stream": true,
397                "input": [{
398                    "type": "message",
399                    "role": "user",
400                    "content": [{"type": "input_text", "text": "forklift"}, media]
401                }],
402                "metadata": {"mask_encoding": "one_bit", "propagation_direction": "forward"}
403            })
404        );
405    }
406
407    #[test]
408    fn the_frame_price_has_the_fifty_frame_minimum() {
409        let sam = SamVideoTracker::new(SamConfig::new("k")).unwrap();
410        let d = VideoAnalyzer::<ReleasedImage>::descriptor(&sam);
411        let price = d.price.as_ref().unwrap();
412        assert_eq!(price.unit(), Some(UsageUnit::Frames));
413        assert_eq!(price.request_cost(1), Some(10_000));
414        assert_eq!(price.request_cost(1_000), Some(200_000));
415        assert_eq!(d.requests_for(3, false), 3);
416    }
417}