adk_vision/stream/pipeline.rs
1//! [`StreamPipeline`]: source, sampler, governor, privacy, detector, tracker and sink.
2
3use std::sync::{Arc, Mutex};
4
5use adk_core::ErrorCategory;
6use async_trait::async_trait;
7use chrono::{DateTime, Utc};
8use futures::StreamExt;
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11
12use super::FrameSource;
13use super::governor::{
14 EscalationDecision, EscalationVerdict, FrameBudget, FrameGovernor, FrameVerdict, GovernorState,
15 GovernorStep,
16};
17use super::privacy::{FramePrivacy, PrivacyHook, RedactedFrame};
18use super::records::{
19 VISION_SOURCE_PAUSED, VISION_SOURCE_RESUMED, VISION_SOURCE_STARTED, VISION_SOURCE_STOPPED,
20 governor_drafts, source_draft,
21};
22use crate::cx::VisionCx;
23use crate::digest::Digest;
24use crate::error::{Result, VisionError};
25use crate::geometry::{Region, TrackId};
26use crate::media::{FrameMeta, FrameSourceId, SourceImage};
27use crate::runtime::{CallOptions, CallRecord, VisionRuntime};
28use crate::traits::{DetectQuery, Sampling, Tracker};
29use crate::watch::{FrameRef, TrackedObservation};
30
31/// One processed frame, as an [`ObservationSink`] receives it.
32///
33/// [`tracked`](Self::tracked) turns it into the [`TrackedObservation`] a
34/// [`WatchEvaluator`](crate::WatchEvaluator) takes.
35#[derive(Clone, Debug)]
36pub struct Observation {
37 /// The frame source.
38 pub source: FrameSourceId,
39 /// The source session: one per [`StreamPipeline::run`], the scope the track identifiers
40 /// belong to and reset with (V-I8).
41 pub session: String,
42 /// The frame's identity and timing.
43 pub frame: FrameMeta,
44 /// The redacted frame, still ephemeral: keep it through a
45 /// [`FrameKeeper`](super::FrameKeeper) to make it evidence.
46 pub image: Arc<RedactedFrame>,
47 /// The digest of the redacted frame's PNG encoding: the regions' image, and the digest
48 /// the frame is stored under if it is kept.
49 pub digest: Digest,
50 /// What the detector found, in source pixels, with the tracker's anonymous track
51 /// identifiers.
52 pub regions: Vec<Region>,
53 /// The tracks the tracker holds after this frame, seen in it or kept through a brief
54 /// miss ([`Tracker::live_tracks`]).
55 pub tracks: Vec<TrackId>,
56 /// The detector's metered calls.
57 pub calls: Vec<CallRecord>,
58}
59
60impl Observation {
61 /// The frame as a watch condition names it: index, capture time, digest and size, with no
62 /// artifact while the frame is ephemeral.
63 pub fn frame_ref(&self) -> FrameRef {
64 let (width, height) = self.image.pixels().size();
65 FrameRef::new(self.frame.index, self.frame.captured_at, self.digest, width, height)
66 }
67
68 /// The observation as a [`WatchEvaluator`](crate::WatchEvaluator) takes it: source,
69 /// session, frame, tracked regions and the tracks the tracker still holds.
70 pub fn tracked(&self) -> TrackedObservation {
71 TrackedObservation::new(
72 self.source.clone(),
73 self.session.clone(),
74 self.frame_ref(),
75 self.regions.clone(),
76 )
77 .with_tracks(self.tracks.iter().copied())
78 }
79}
80
81/// Why a stream stopped.
82#[non_exhaustive]
83#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
85pub enum StopCause {
86 /// The source ended: a file's last frame, a camera that hung up.
87 Ended,
88 /// The run was cancelled.
89 Cancelled,
90 /// A stage failed.
91 Failed {
92 /// The error's code.
93 code: String,
94 /// The error's message.
95 message: String,
96 },
97}
98
99/// A change in a stream's life, as an [`ObservationSink`] receives it. Each is also a
100/// `vision.source.*` or `vision.governor.step` audit record.
101#[non_exhaustive]
102#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
103#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
104pub enum SourceEvent {
105 /// Frames started.
106 Started {
107 /// The sampling asked of the source.
108 sampling: Sampling,
109 },
110 /// The frame governor changed the stream.
111 Governor {
112 /// The change.
113 step: GovernorStep,
114 },
115 /// The kill switch froze the run; frames are dropped until it thaws.
116 Frozen,
117 /// The kill switch thawed; frames are processed again.
118 Thawed,
119 /// Frames stopped.
120 Stopped {
121 /// Why.
122 cause: StopCause,
123 },
124}
125
126/// Receives a stream's observations: watch conditions and wakes, the live camera surface, a
127/// recorder.
128///
129/// The pipeline awaits each call before it reads the next frame, so a slow sink slows the
130/// stream and the source drops the frames it cannot hold; a sink that fans out to slower
131/// consumers should queue on its own. An error stops the stream.
132///
133/// # Example
134///
135/// ```
136/// use std::sync::Mutex;
137/// use adk_vision::VisionCx;
138/// use adk_vision::stream::{Observation, ObservationSink};
139///
140/// /// Counts the regions of each label it sees.
141/// #[derive(Default)]
142/// struct Counter(Mutex<std::collections::BTreeMap<String, usize>>);
143///
144/// #[async_trait::async_trait]
145/// impl ObservationSink for Counter {
146/// async fn observe(&self, _cx: &VisionCx, observation: Observation) -> adk_vision::Result<()> {
147/// let mut counts = self.0.lock().unwrap();
148/// for region in &observation.regions {
149/// *counts.entry(region.label.clone().unwrap_or_default()).or_default() += 1;
150/// }
151/// Ok(())
152/// }
153/// }
154/// ```
155///
156/// # Watch conditions and wakes
157///
158/// An observation converts to the [`TrackedObservation`] a
159/// [`WatchEvaluator`](crate::WatchEvaluator) takes. A sink that holds watch conditions keeps
160/// the frame of each event as its wake payload, so the frame is stored redacted, and hands the
161/// event with the frame's artifact to a [`WatchSink`](crate::WatchSink) such as the kernel's
162/// `VisionWakeSource`. [`StreamWatch`](super::StreamWatch) is that sink, with the
163/// `vision.watch.fired` record; in outline:
164///
165/// ```
166/// use std::sync::{Arc, Mutex};
167/// use adk_vision::stream::{FrameKeeper, KeepReason, Observation, ObservationSink};
168/// use adk_vision::{VisionCx, WatchEvaluator, WatchSink};
169///
170/// struct Watch {
171/// evaluator: Mutex<WatchEvaluator>,
172/// keeper: FrameKeeper,
173/// wakes: Arc<dyn WatchSink>,
174/// }
175///
176/// #[async_trait::async_trait]
177/// impl ObservationSink for Watch {
178/// async fn observe(&self, cx: &VisionCx, observation: Observation) -> adk_vision::Result<()> {
179/// let events = self.evaluator.lock().unwrap().observe(&observation.tracked());
180/// for event in events {
181/// let kept = self.keeper.keep(cx, &observation.image, KeepReason::WakePayload).await?;
182/// self.wakes.deliver(&event.with_frame_artifact(kept.image.artifact)).await?;
183/// }
184/// Ok(())
185/// }
186/// }
187/// ```
188#[async_trait]
189pub trait ObservationSink: Send + Sync {
190 /// One processed frame.
191 ///
192 /// # Errors
193 ///
194 /// Any failure; the stream stops with it.
195 async fn observe(&self, cx: &VisionCx, observation: Observation) -> Result<()>;
196
197 /// A change in the stream's life. Does nothing by default.
198 ///
199 /// # Errors
200 ///
201 /// Any failure; the stream stops with it, except after it has stopped.
202 async fn source_event(&self, _cx: &VisionCx, _event: &SourceEvent) -> Result<()> {
203 Ok(())
204 }
205}
206
207/// What a finished stream did.
208#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
209#[serde(rename_all = "camelCase")]
210pub struct StreamSummary {
211 /// Frames the source delivered.
212 pub received: u64,
213 /// Frames the governor thinned.
214 pub thinned: u64,
215 /// Frames dropped while the governor paused the source.
216 pub paused: u64,
217 /// Frames dropped while the kill switch was frozen.
218 pub frozen: u64,
219 /// Frames dropped because the privacy hook failed.
220 pub privacy_failures: u64,
221 /// Frames skipped because the detector was briefly unavailable.
222 pub detection_errors: u64,
223 /// Observations delivered to the sink.
224 pub observations: u64,
225}
226
227/// The stream's frame governor, shared with whatever escalates its tracks.
228///
229/// Escalation requests and frames go through the same governor, so its quotas cover both;
230/// each change it makes writes its `vision.governor.step` record.
231#[derive(Clone)]
232pub struct GovernorHandle {
233 source: FrameSourceId,
234 governor: Arc<Mutex<FrameGovernor>>,
235}
236
237impl std::fmt::Debug for GovernorHandle {
238 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239 f.debug_struct("GovernorHandle").field("source", &self.source).finish_non_exhaustive()
240 }
241}
242
243impl GovernorHandle {
244 fn lock(&self) -> std::sync::MutexGuard<'_, FrameGovernor> {
245 self.governor.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
246 }
247
248 /// The governor's state now.
249 pub fn state(&self) -> GovernorState {
250 self.lock().state()
251 }
252
253 /// Asks to escalate `frames` frames now: granted with the frames it is billed, or
254 /// refused with the reason. Changes are recorded on `cx`'s audit trail.
255 ///
256 /// # Errors
257 ///
258 /// The audit trail's error when it fails closed.
259 pub async fn request_escalation(
260 &self,
261 cx: &VisionCx,
262 frames: u64,
263 ) -> Result<EscalationVerdict> {
264 self.request_escalation_at(cx, Utc::now(), frames).await
265 }
266
267 /// As [`request_escalation`](Self::request_escalation), at `at`.
268 ///
269 /// # Errors
270 ///
271 /// The audit trail's error when it fails closed.
272 pub async fn request_escalation_at(
273 &self,
274 cx: &VisionCx,
275 at: DateTime<Utc>,
276 frames: u64,
277 ) -> Result<EscalationVerdict> {
278 let EscalationDecision { verdict, steps } = self.lock().request_escalation(at, frames);
279 for step in &steps {
280 for draft in governor_drafts(&self.source, step) {
281 cx.audit(draft).await?;
282 }
283 }
284 Ok(verdict)
285 }
286
287 fn offer(&self, at: DateTime<Utc>) -> (FrameVerdict, Vec<GovernorStep>) {
288 let admission = self.lock().offer(at);
289 (admission.verdict, admission.steps)
290 }
291}
292
293struct Detection {
294 runtime: Arc<VisionRuntime>,
295 query: DetectQuery,
296 options: CallOptions,
297}
298
299/// Runs one [`FrameSource`] through the stages of spec 3.7 ยง7.13 and hands each processed
300/// frame to an [`ObservationSink`].
301///
302/// | Stage | What it does |
303/// |-------|--------------|
304/// | Source and sampler | Frames at the sampling rate and size; the source drops what the pipeline cannot keep up with |
305/// | Frame governor | Thins, or pauses, frames to the [`FrameBudget`]; records each change |
306/// | Privacy | The [`PrivacyHook`] of [`with_privacy`](StreamPipelineBuilder::with_privacy), when one is given, redacts every frame first; a failing hook drops the frame |
307/// | Detector | [`VisionRuntime::detect_with`], metered in frames, regions in source pixels |
308/// | Tracker | Anonymous track identifiers, reset when the stream starts and stops (V-I8) |
309/// | Sink | [`ObservationSink::observe`] |
310///
311/// The run writes `vision.source.started` and `vision.source.stopped`, the governor's
312/// steps, and `vision.source.paused` and `.resumed` around a kill-switch freeze, to the
313/// audit trail of the [`VisionCx`] it runs under.
314///
315/// # Example
316///
317/// ```
318/// use std::sync::{Arc, Mutex};
319/// use adk_vision::stream::{FrameSource, FrameStream, Observation, ObservationSink, StreamPipeline};
320/// use adk_vision::{DecodedImage, Frame, FramePixels, FrameSourceId, Sampling, VisionCx};
321/// use futures::StreamExt;
322///
323/// struct Three(FrameSourceId);
324///
325/// #[async_trait::async_trait]
326/// impl FrameSource for Three {
327/// fn id(&self) -> &FrameSourceId {
328/// &self.0
329/// }
330/// async fn frames(&self, _sampling: Sampling) -> adk_vision::Result<FrameStream> {
331/// let id = self.0.clone();
332/// Ok(futures::stream::iter((0..3u64).map(move |index| {
333/// Ok(Frame {
334/// source: id.clone(),
335/// index,
336/// pts: std::time::Duration::from_secs(index),
337/// captured_at: chrono::Utc::now(),
338/// pixels: FramePixels::Ephemeral(Arc::new(DecodedImage::filled(4, 4, [9; 4]))),
339/// })
340/// }))
341/// .boxed())
342/// }
343/// }
344///
345/// #[derive(Default)]
346/// struct Seen(Mutex<Vec<u64>>);
347///
348/// #[async_trait::async_trait]
349/// impl ObservationSink for Seen {
350/// async fn observe(&self, _cx: &VisionCx, o: Observation) -> adk_vision::Result<()> {
351/// self.0.lock().unwrap().push(o.frame.index);
352/// Ok(())
353/// }
354/// }
355///
356/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
357/// let seen = Arc::new(Seen::default());
358/// let pipeline = StreamPipeline::builder(Arc::new(Three(FrameSourceId("cam".into()))))
359/// .sampling(Sampling { fps: 1.0, max_long_edge: None })
360/// .sink(seen.clone())
361/// .build()
362/// .unwrap();
363/// let summary = pipeline.run(&VisionCx::new()).await.unwrap();
364/// assert_eq!(summary.observations, 3);
365/// assert_eq!(*seen.0.lock().unwrap(), vec![0, 1, 2]);
366/// # });
367/// ```
368pub struct StreamPipeline {
369 source: Arc<dyn FrameSource>,
370 sampling: Sampling,
371 privacy: FramePrivacy,
372 detection: Option<Detection>,
373 // A `Mutex` makes the pipeline `Sync`, so its run is a `Send` future, though a tracker
374 // is only `Send`; it is locked only between awaits.
375 tracker: Option<Mutex<Box<dyn Tracker>>>,
376 governor: Option<GovernorHandle>,
377 sink: Arc<dyn ObservationSink>,
378}
379
380impl std::fmt::Debug for StreamPipeline {
381 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
382 f.debug_struct("StreamPipeline")
383 .field("source", self.source.id())
384 .field("sampling", &self.sampling)
385 .field("privacy", &self.privacy)
386 .field("governor", &self.governor)
387 .finish_non_exhaustive()
388 }
389}
390
391/// Builds a [`StreamPipeline`]. Frames are not redacted unless a hook is given with
392/// [`with_privacy`](Self::with_privacy).
393pub struct StreamPipelineBuilder {
394 source: Arc<dyn FrameSource>,
395 privacy: Arc<dyn PrivacyHook>,
396 sampling: Option<Sampling>,
397 detection: Option<Detection>,
398 tracker: Option<Box<dyn Tracker>>,
399 budget: Option<FrameBudget>,
400 sink: Option<Arc<dyn ObservationSink>>,
401}
402
403/// A sink that drops every observation, for a pipeline built without one.
404struct Discard;
405
406#[async_trait]
407impl ObservationSink for Discard {
408 async fn observe(&self, _cx: &VisionCx, _observation: Observation) -> Result<()> {
409 Ok(())
410 }
411}
412
413impl StreamPipelineBuilder {
414 /// Passes every frame through `hook` before any other stage sees it, such as
415 /// [`RedactorPrivacy::blur_faces`](super::RedactorPrivacy::blur_faces); a frame the hook
416 /// fails on is dropped.
417 pub fn with_privacy(mut self, hook: Arc<dyn PrivacyHook>) -> Self {
418 self.privacy = hook;
419 self
420 }
421
422 /// Samples the source at `sampling`. Defaults to the budget's local rate when a
423 /// [`budget`](Self::budget) is set, and to one frame a second otherwise.
424 pub fn sampling(mut self, sampling: Sampling) -> Self {
425 self.sampling = Some(sampling);
426 self
427 }
428
429 /// Detects `query` on every processed frame through `runtime`'s detection route. Each
430 /// call is metered in [`UsageUnit::Frames`](adk_core::UsageUnit::Frames), so a stream
431 /// counts against frame caps and quotas, not image ones (spec 3.7 X3).
432 pub fn detector(mut self, runtime: Arc<VisionRuntime>, query: DetectQuery) -> Self {
433 self.detection =
434 Some(Detection { runtime, query, options: CallOptions::default().as_frames() });
435 self
436 }
437
438 /// Sets the detection call's options: a route, a region of interest. The calls stay
439 /// metered as frames.
440 pub fn detect_options(mut self, options: CallOptions) -> Self {
441 if let Some(detection) = &mut self.detection {
442 detection.options = options.as_frames();
443 }
444 self
445 }
446
447 /// Tracks detections across frames.
448 pub fn tracker(mut self, tracker: Box<dyn Tracker>) -> Self {
449 self.tracker = Some(tracker);
450 self
451 }
452
453 /// Holds the stream to `budget` through a [`FrameGovernor`].
454 pub fn budget(mut self, budget: FrameBudget) -> Self {
455 self.budget = Some(budget);
456 self
457 }
458
459 /// Hands observations and source events to `sink`.
460 pub fn sink(mut self, sink: Arc<dyn ObservationSink>) -> Self {
461 self.sink = Some(sink);
462 self
463 }
464
465 /// Builds the pipeline.
466 ///
467 /// # Errors
468 ///
469 /// [`VisionError::InvalidInput`] for an invalid budget or sampling rate.
470 pub fn build(self) -> Result<StreamPipeline> {
471 let governor = match self.budget {
472 Some(budget) => Some(GovernorHandle {
473 source: self.source.id().clone(),
474 governor: Arc::new(Mutex::new(FrameGovernor::new(budget)?)),
475 }),
476 None => None,
477 };
478 let sampling = self.sampling.unwrap_or_else(|| Sampling {
479 fps: governor.as_ref().map_or(1.0, |g| g.lock().budget().local_fps),
480 max_long_edge: None,
481 });
482 super::Sampler::new(sampling)?;
483 Ok(StreamPipeline {
484 source: self.source,
485 sampling,
486 privacy: FramePrivacy::new(self.privacy),
487 detection: self.detection,
488 tracker: self.tracker.map(Mutex::new),
489 governor,
490 sink: self.sink.unwrap_or_else(|| Arc::new(Discard)),
491 })
492 }
493}
494
495impl StreamPipeline {
496 /// A builder over `source`, its frames unredacted until
497 /// [`with_privacy`](StreamPipelineBuilder::with_privacy) gives a hook.
498 pub fn builder(source: Arc<dyn FrameSource>) -> StreamPipelineBuilder {
499 StreamPipelineBuilder {
500 source,
501 privacy: Arc::new(super::NoRedaction),
502 sampling: None,
503 detection: None,
504 tracker: None,
505 budget: None,
506 sink: None,
507 }
508 }
509
510 /// The source's identifier.
511 pub fn source_id(&self) -> &FrameSourceId {
512 self.source.id()
513 }
514
515 /// The frame governor, when the pipeline has a budget: escalations go through it.
516 pub fn governor(&self) -> Option<GovernorHandle> {
517 self.governor.clone()
518 }
519
520 /// Forgets every track: identifiers restart with each source session (V-I8).
521 fn reset_tracker(&self) {
522 if let Some(tracker) = &self.tracker {
523 tracker.lock().unwrap_or_else(std::sync::PoisonError::into_inner).reset();
524 }
525 }
526
527 async fn event(&self, cx: &VisionCx, event: SourceEvent) -> Result<()> {
528 self.sink.source_event(cx, &event).await
529 }
530
531 async fn governor_steps(&self, cx: &VisionCx, steps: Vec<GovernorStep>) -> Result<()> {
532 let id = self.source.id();
533 for step in steps {
534 for draft in governor_drafts(id, &step) {
535 cx.audit(draft).await?;
536 }
537 self.event(cx, SourceEvent::Governor { step }).await?;
538 }
539 Ok(())
540 }
541
542 /// Runs the stream until the source ends, `cx` is cancelled, or a stage fails.
543 ///
544 /// # Errors
545 ///
546 /// The source's error opening or reading frames, a detector error other than a brief
547 /// unavailability (a budget refusal stops the stream), the sink's error, or the audit
548 /// trail's when it fails closed. A frozen kill switch at the start refuses the run.
549 pub async fn run(self, cx: &VisionCx) -> Result<StreamSummary> {
550 cx.check()?;
551 let id = self.source.id().clone();
552 let mut frames = self.source.frames(self.sampling).await?;
553 let budget = self.governor.as_ref().map(|g| g.lock().budget().clone());
554 let session = uuid::Uuid::new_v4().to_string();
555 cx.audit(source_draft(
556 VISION_SOURCE_STARTED,
557 &id,
558 json!({
559 "session": session,
560 "sampling": self.sampling,
561 "budget": budget,
562 "privacy": self.privacy.hook_name(),
563 }),
564 ))
565 .await?;
566 tracing::info!(stream.source = %id.0, stream.fps = self.sampling.fps, "stream started");
567 self.reset_tracker();
568 let mut summary = StreamSummary::default();
569 let outcome = match self.event(cx, SourceEvent::Started { sampling: self.sampling }).await {
570 Ok(()) => self.process(cx, &session, &mut frames, &mut summary).await,
571 Err(err) => Err(err),
572 };
573 drop(frames);
574 self.reset_tracker();
575 let cause = match &outcome {
576 Ok(cause) => cause.clone(),
577 Err(err) => {
578 StopCause::Failed { code: err.code().to_string(), message: err.to_string() }
579 }
580 };
581 tracing::info!(
582 stream.source = %id.0,
583 stream.received = summary.received,
584 stream.observations = summary.observations,
585 "stream stopped"
586 );
587 let recorded = cx
588 .audit(source_draft(
589 VISION_SOURCE_STOPPED,
590 &id,
591 json!({ "session": session, "cause": cause, "summary": summary }),
592 ))
593 .await;
594 // The stream is over: a sink error here has nothing left to stop.
595 if let Err(err) = self.event(cx, SourceEvent::Stopped { cause }).await {
596 tracing::warn!(stream.source = %id.0, error = %err, "sink refused the stop event");
597 }
598 outcome?;
599 recorded?;
600 Ok(summary)
601 }
602
603 async fn process(
604 &self,
605 cx: &VisionCx,
606 session: &str,
607 frames: &mut super::FrameStream,
608 summary: &mut StreamSummary,
609 ) -> Result<StopCause> {
610 let id = self.source.id().clone();
611 let mut frozen = false;
612 loop {
613 let next = tokio::select! {
614 biased;
615 () = cx.cancellation().cancelled() => return Ok(StopCause::Cancelled),
616 next = frames.next() => next,
617 };
618 let Some(frame) = next else { return Ok(StopCause::Ended) };
619 let frame = frame?;
620 summary.received += 1;
621
622 // The kill switch pauses the stream at its next frame (V-I17).
623 match cx.check() {
624 Err(VisionError::Cancelled) => return Ok(StopCause::Cancelled),
625 Err(err) => {
626 summary.frozen += 1;
627 if !frozen {
628 frozen = true;
629 tracing::warn!(stream.source = %id.0, error = %err, "stream paused by the kill switch");
630 cx.audit(source_draft(
631 VISION_SOURCE_PAUSED,
632 &id,
633 json!({ "reason": "frozen", "code": err.code() }),
634 ))
635 .await?;
636 self.event(cx, SourceEvent::Frozen).await?;
637 }
638 continue;
639 }
640 Ok(()) if frozen => {
641 frozen = false;
642 cx.audit(source_draft(
643 VISION_SOURCE_RESUMED,
644 &id,
645 json!({ "reason": "thawed" }),
646 ))
647 .await?;
648 self.event(cx, SourceEvent::Thawed).await?;
649 }
650 Ok(()) => {}
651 }
652
653 if let Some(governor) = &self.governor {
654 let (verdict, steps) = governor.offer(frame.captured_at);
655 self.governor_steps(cx, steps).await?;
656 match verdict {
657 FrameVerdict::Process => {}
658 FrameVerdict::Thinned => {
659 summary.thinned += 1;
660 continue;
661 }
662 FrameVerdict::Paused => {
663 summary.paused += 1;
664 continue;
665 }
666 }
667 }
668
669 let meta = frame.meta();
670 let redacted = match self.privacy.apply(cx, frame).await {
671 Ok(redacted) => Arc::new(redacted),
672 Err(VisionError::Cancelled) => return Ok(StopCause::Cancelled),
673 Err(err) => {
674 // Fail closed: a frame the hook could not redact goes nowhere.
675 summary.privacy_failures += 1;
676 tracing::warn!(stream.source = %id.0, frame.index = meta.index, error = %err, "frame dropped: privacy hook failed");
677 continue;
678 }
679 };
680 let pixels = redacted.shared_pixels();
681 let digest = Digest::of(&pixels.encode_png()?);
682 let (regions, calls) = match &self.detection {
683 None => (Vec::new(), Vec::new()),
684 Some(detection) => {
685 let image = SourceImage::from_parts(digest, "image/png".into(), pixels);
686 match detection
687 .runtime
688 .detect_with(cx, &image, &detection.query, &detection.options)
689 .await
690 {
691 Ok(found) => (found.value, found.calls),
692 Err(VisionError::Cancelled) => return Ok(StopCause::Cancelled),
693 Err(err)
694 if matches!(
695 err.category(),
696 ErrorCategory::RateLimited
697 | ErrorCategory::Timeout
698 | ErrorCategory::Unavailable
699 ) =>
700 {
701 summary.detection_errors += 1;
702 tracing::warn!(stream.source = %id.0, frame.index = meta.index, error = %err, "frame skipped: detector unavailable");
703 continue;
704 }
705 Err(err) => return Err(err),
706 }
707 }
708 };
709 let (regions, tracks) = match &self.tracker {
710 Some(tracker) => {
711 let mut tracker =
712 tracker.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
713 let regions = tracker.update(&meta, regions);
714 (regions, tracker.live_tracks())
715 }
716 None => (regions, Vec::new()),
717 };
718 self.sink
719 .observe(
720 cx,
721 Observation {
722 source: id.clone(),
723 session: session.to_string(),
724 frame: meta,
725 image: redacted,
726 digest,
727 regions,
728 tracks,
729 calls,
730 },
731 )
732 .await?;
733 summary.observations += 1;
734 }
735 }
736}