Skip to main content

adk_vision/stream/
privacy.rs

1//! The privacy step every stream frame passes before anything else sees it (spec 3.7
2//! §7.13, V-I9, S18).
3
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8
9use crate::cx::VisionCx;
10use crate::digest::Digest;
11use crate::edit::{Rgba, ops};
12use crate::egress::Redactor;
13use crate::error::{Result, VisionError};
14use crate::geometry::{BBox, TransformChain};
15use crate::media::{DecodedImage, Frame, FrameMeta, FramePixels, FrameSourceId};
16use crate::redact::REDACTION_MARGIN;
17use crate::sent::SentImage;
18
19/// Redacts a frame's pixels in place before any other stage sees them: the face blur of
20/// spec 3.7 S18 ([`RedactorPrivacy::blur_faces`]), any [`RedactorPrivacy`], or a hook of
21/// your own.
22///
23/// A hook that fails fails closed: the pipeline drops the frame, so nothing downstream sees
24/// or stores it.
25///
26/// # Example
27///
28/// ```
29/// use adk_vision::stream::PrivacyHook;
30/// use adk_vision::{BBox, DecodedImage, FrameMeta, VisionCx};
31///
32/// /// Blacks out a fixed window a camera can see into.
33/// struct Window;
34///
35/// #[async_trait::async_trait]
36/// impl PrivacyHook for Window {
37///     fn name(&self) -> &str {
38///         "window"
39///     }
40///
41///     async fn redact(
42///         &self,
43///         _cx: &VisionCx,
44///         _frame: &FrameMeta,
45///         pixels: &mut DecodedImage,
46///     ) -> adk_vision::Result<Vec<BBox>> {
47///         let (w, _) = pixels.size();
48///         Ok(vec![BBox::new(w as f32 / 2.0, 0.0, w as f32, 40.0)])
49///     }
50/// }
51/// ```
52#[async_trait]
53pub trait PrivacyHook: Send + Sync {
54    /// The hook's name, recorded with every frame it passed: `none` for [`NoRedaction`].
55    fn name(&self) -> &str;
56
57    /// Redacts `pixels` in place and returns the boxes it redacted, in the frame's pixels.
58    ///
59    /// # Errors
60    ///
61    /// Any failure: a detector that cannot load, a cancelled call. The frame is dropped.
62    async fn redact(
63        &self,
64        cx: &VisionCx,
65        frame: &FrameMeta,
66        pixels: &mut DecodedImage,
67    ) -> Result<Vec<BBox>>;
68}
69
70/// Redacts nothing: the privacy step of a pipeline, source or camera given no hook. Kept
71/// frames record `none` as their privacy step.
72#[derive(Clone, Copy, Debug, Default)]
73pub struct NoRedaction;
74
75#[async_trait]
76impl PrivacyHook for NoRedaction {
77    fn name(&self) -> &str {
78        "none"
79    }
80
81    async fn redact(
82        &self,
83        _cx: &VisionCx,
84        _frame: &FrameMeta,
85        _pixels: &mut DecodedImage,
86    ) -> Result<Vec<BBox>> {
87        Ok(Vec::new())
88    }
89}
90
91/// How [`RedactorPrivacy`] hides what its redactor finds.
92#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
93#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
94pub enum RedactionMethod {
95    /// Solid black: cannot be reversed.
96    Fill,
97    /// Gaussian blur of this standard deviation, in pixels.
98    Blur {
99        /// The standard deviation.
100        sigma: f32,
101    },
102    /// Square blocks of this size, in pixels.
103    Pixelate {
104        /// The block size.
105        block: u32,
106    },
107    /// Gaussian blur whose standard deviation is this share of each box's longer side, so a
108    /// face near the camera is blurred as hard as a far one. At
109    /// [`FACE_BLUR`](RedactionMethod::FACE_BLUR) YuNet no longer finds the face it blurred.
110    ScaledBlur {
111        /// The share of the box's longer side.
112        fraction: f32,
113    },
114}
115
116impl RedactionMethod {
117    /// The face blur of spec 3.7 S18: a standard deviation of a quarter of the face box.
118    pub const FACE_BLUR: Self = Self::ScaledBlur { fraction: 0.25 };
119}
120
121/// A [`PrivacyHook`] over any on-device egress [`Redactor`]: the boxes it finds, plus a
122/// two-pixel margin, are filled, blurred or pixelated.
123///
124/// Over [`FaceRedactor`](crate::FaceRedactor) with [`RedactionMethod::FACE_BLUR`] it is the
125/// face blur of spec 3.7 S18 ([`blur_faces`](Self::blur_faces)): each face blurred, each
126/// person the face detector finds no face for blurred whole. Over
127/// [`PersonRedactor`](crate::PersonRedactor) it covers every detected person whole.
128///
129/// # Example
130///
131/// ```
132/// use std::sync::Arc;
133/// use adk_vision::stream::{RedactionMethod, RedactorPrivacy};
134/// use adk_vision::{BBox, RedactionClass, Redactor, SentImage, VisionCx};
135///
136/// struct Corner;
137///
138/// #[async_trait::async_trait]
139/// impl Redactor for Corner {
140///     fn class(&self) -> RedactionClass {
141///         RedactionClass::faces()
142///     }
143///     async fn find(&self, _cx: &VisionCx, _image: &SentImage) -> adk_vision::Result<Vec<BBox>> {
144///         Ok(vec![BBox::new(0.0, 0.0, 8.0, 8.0)])
145///     }
146/// }
147///
148/// let hook = RedactorPrivacy::new(Arc::new(Corner), RedactionMethod::Fill);
149/// assert_eq!(adk_vision::stream::PrivacyHook::name(&hook), "redactor:faces");
150/// ```
151pub struct RedactorPrivacy {
152    redactor: Arc<dyn Redactor>,
153    method: RedactionMethod,
154    name: String,
155    hold: u64,
156    /// Each source's boxes found in its latest frames, by frame index.
157    held: std::sync::Mutex<std::collections::HashMap<FrameSourceId, Vec<(u64, BBox)>>>,
158}
159
160/// How much a held box grows per frame it is held, as a share of its longer side.
161const HOLD_GROWTH: f32 = 0.25;
162
163impl std::fmt::Debug for RedactorPrivacy {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        f.debug_struct("RedactorPrivacy")
166            .field("name", &self.name)
167            .field("method", &self.method)
168            .field("hold", &self.hold)
169            .finish_non_exhaustive()
170    }
171}
172
173impl RedactorPrivacy {
174    /// Redacts what `redactor` finds with `method`.
175    pub fn new(redactor: Arc<dyn Redactor>, method: RedactionMethod) -> Self {
176        let name = format!("redactor:{}", redactor.class());
177        Self { redactor, method, name, hold: 0, held: std::sync::Mutex::default() }
178    }
179
180    /// Holds each box for `frames` more frames of its source: a box found in one of the
181    /// last `frames` frames that nothing found in this frame overlaps is redacted again,
182    /// widened by a quarter of its longer side per frame since, because a detector misses a
183    /// moving face for a frame now and then. Nothing is held by default.
184    pub fn with_hold(mut self, frames: u64) -> Self {
185        self.hold = frames;
186        self
187    }
188
189    /// Blurs faces on the device before anything is written (spec 3.7 S18, V-I9):
190    /// [`FaceRedactor::on_device`](crate::FaceRedactor::on_device) — YuNet, with RF-DETR
191    /// Nano covering each person it finds no face for — under
192    /// [`RedactionMethod::FACE_BLUR`] (feature `onnx`).
193    ///
194    /// Each face is held for two more frames ([`with_hold`](Self::with_hold)), so a frame in
195    /// which YuNet misses a face it found just before still has it blurred. The models load
196    /// on the first frame. A frame whose redactor fails is dropped, so no later stage sees,
197    /// and no keeper stores, a frame that was not redacted.
198    ///
199    /// # Example
200    ///
201    /// ```
202    /// use std::sync::Arc;
203    /// use adk_vision::stream::{PrivacyHook, RedactorPrivacy};
204    /// use adk_vision::{FetchConfig, InMemoryAcceptanceStore, ModelFetcher};
205    ///
206    /// let fetcher =
207    ///     ModelFetcher::new(FetchConfig::from_env(), Arc::new(InMemoryAcceptanceStore::new()));
208    /// let hook = RedactorPrivacy::blur_faces(fetcher);
209    /// assert_eq!(hook.name(), "redactor:faces");
210    /// ```
211    #[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
212    pub fn blur_faces(fetcher: crate::ModelFetcher) -> Self {
213        Self::new(Arc::new(crate::FaceRedactor::on_device(fetcher)), RedactionMethod::FACE_BLUR)
214            .with_hold(2)
215    }
216}
217
218#[async_trait]
219impl PrivacyHook for RedactorPrivacy {
220    fn name(&self) -> &str {
221        &self.name
222    }
223
224    async fn redact(
225        &self,
226        cx: &VisionCx,
227        frame: &FrameMeta,
228        pixels: &mut DecodedImage,
229    ) -> Result<Vec<BBox>> {
230        let (w, h) = pixels.size();
231        // The digest only labels this ephemeral view for the redactor; an ephemeral frame
232        // has no encoded form to hash, and the raw pixels identify it as well.
233        let view = SentImage::new(
234            Digest::of(pixels.rgba()),
235            Arc::new(pixels.clone()),
236            TransformChain::new(w, h),
237        );
238        let found = self.redactor.find(cx, &view).await?;
239        let mut boxes = found.clone();
240        if self.hold > 0 {
241            let mut held = self.held.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
242            let recent = held.entry(frame.source.clone()).or_default();
243            // A source that starts again numbers its frames from zero: nothing carries over.
244            recent.retain(|(then, _)| frame.index > *then && frame.index - then <= self.hold);
245            for (then, bbox) in recent.iter() {
246                let age = (frame.index - then) as f32;
247                let grown = bbox
248                    .expanded(HOLD_GROWTH * age * bbox.width().max(bbox.height()))
249                    .clamped(w, h);
250                if !found.iter().any(|f| f.intersection(&grown).is_some()) {
251                    boxes.push(grown);
252                }
253            }
254            recent.extend(found.iter().map(|bbox| (frame.index, *bbox)));
255        }
256        let mut redacted = Vec::with_capacity(boxes.len());
257        for bbox in boxes {
258            let padded = BBox::new(
259                bbox.x0 - REDACTION_MARGIN,
260                bbox.y0 - REDACTION_MARGIN,
261                bbox.x1 + REDACTION_MARGIN,
262                bbox.y1 + REDACTION_MARGIN,
263            );
264            match self.method {
265                RedactionMethod::Fill => {
266                    ops::fill(pixels, &padded, Rgba([0, 0, 0, 255]));
267                }
268                RedactionMethod::Blur { sigma } => ops::blur(pixels, &padded, sigma),
269                RedactionMethod::Pixelate { block } => ops::pixelate(pixels, &padded, block.max(2)),
270                RedactionMethod::ScaledBlur { fraction } => {
271                    let sigma = fraction * padded.width().max(padded.height());
272                    ops::fast_blur(pixels, &padded, sigma);
273                }
274            }
275            redacted.push(padded);
276        }
277        Ok(redacted)
278    }
279}
280
281/// A frame that has passed a [`PrivacyHook`]: the only form of a frame the pipeline's later
282/// stages see and [`FrameKeeper`](super::FrameKeeper) stores.
283///
284/// [`FramePrivacy::apply`] is the only way to make one, so an unredacted frame cannot reach
285/// an artifact write (V-I9):
286///
287/// ```compile_fail,E0451
288/// use std::sync::Arc;
289/// use adk_vision::stream::RedactedFrame;
290/// use adk_vision::{DecodedImage, FrameMeta, FrameSourceId};
291///
292/// let meta = FrameMeta { source: FrameSourceId("cam".into()), index: 0, pts_ms: 0, captured_at: chrono::Utc::now() };
293/// let forged = RedactedFrame { meta, pixels: Arc::new(DecodedImage::filled(1, 1, [0; 4])), hook: "none".into(), redacted: vec![] };
294/// ```
295#[derive(Clone, Debug)]
296pub struct RedactedFrame {
297    meta: FrameMeta,
298    pixels: Arc<DecodedImage>,
299    hook: String,
300    redacted: Vec<BBox>,
301}
302
303impl RedactedFrame {
304    /// The frame's identity and timing.
305    pub fn meta(&self) -> &FrameMeta {
306        &self.meta
307    }
308
309    /// The redacted pixels.
310    pub fn pixels(&self) -> &DecodedImage {
311        &self.pixels
312    }
313
314    pub(crate) fn shared_pixels(&self) -> Arc<DecodedImage> {
315        Arc::clone(&self.pixels)
316    }
317
318    /// The name of the hook the frame passed.
319    pub fn hook(&self) -> &str {
320        &self.hook
321    }
322
323    /// The boxes the hook redacted, in the frame's pixels.
324    pub fn redacted(&self) -> &[BBox] {
325        &self.redacted
326    }
327}
328
329/// Runs frames through a [`PrivacyHook`].
330///
331/// # Example
332///
333/// ```
334/// use std::sync::Arc;
335/// use adk_vision::stream::{FramePrivacy, NoRedaction};
336/// use adk_vision::{DecodedImage, Frame, FramePixels, FrameSourceId, VisionCx};
337///
338/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
339/// let privacy = FramePrivacy::new(Arc::new(NoRedaction));
340/// let frame = Frame {
341///     source: FrameSourceId("line-1".into()),
342///     index: 0,
343///     pts: std::time::Duration::ZERO,
344///     captured_at: chrono::Utc::now(),
345///     pixels: FramePixels::Ephemeral(Arc::new(DecodedImage::filled(4, 4, [0; 4]))),
346/// };
347/// let redacted = privacy.apply(&VisionCx::new(), frame).await.unwrap();
348/// assert_eq!(redacted.hook(), "none");
349/// # });
350/// ```
351#[derive(Clone)]
352pub struct FramePrivacy {
353    hook: Arc<dyn PrivacyHook>,
354}
355
356impl std::fmt::Debug for FramePrivacy {
357    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358        f.debug_struct("FramePrivacy").field("hook", &self.hook.name()).finish()
359    }
360}
361
362impl FramePrivacy {
363    /// Frames through `hook`.
364    pub fn new(hook: Arc<dyn PrivacyHook>) -> Self {
365        Self { hook }
366    }
367
368    /// The hook's name.
369    pub fn hook_name(&self) -> &str {
370        self.hook.name()
371    }
372
373    /// Redacts `frame`.
374    ///
375    /// # Errors
376    ///
377    /// The hook's error, or [`VisionError::InvalidInput`] for a frame that is already stored:
378    /// it passed its privacy step before its write.
379    pub async fn apply(&self, cx: &VisionCx, frame: Frame) -> Result<RedactedFrame> {
380        let meta = frame.meta();
381        let shared = match frame.pixels {
382            FramePixels::Ephemeral(pixels) => pixels,
383            FramePixels::Stored(image) => {
384                return Err(VisionError::InvalidInput(format!(
385                    "frame {} of `{}` is already stored as {}; a stored frame was redacted before its write",
386                    meta.index, meta.source.0, image.digest
387                )));
388            }
389        };
390        let mut pixels = Arc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone());
391        let redacted = self.hook.redact(cx, &meta, &mut pixels).await?;
392        Ok(RedactedFrame {
393            meta,
394            pixels: Arc::new(pixels),
395            hook: self.hook.name().to_string(),
396            redacted,
397        })
398    }
399}