use std::sync::Arc;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use crate::cx::VisionCx;
use crate::digest::Digest;
use crate::edit::{Rgba, ops};
use crate::egress::Redactor;
use crate::error::{Result, VisionError};
use crate::geometry::{BBox, TransformChain};
use crate::media::{DecodedImage, Frame, FrameMeta, FramePixels, FrameSourceId};
use crate::redact::REDACTION_MARGIN;
use crate::sent::SentImage;
#[async_trait]
pub trait PrivacyHook: Send + Sync {
fn name(&self) -> &str;
async fn redact(
&self,
cx: &VisionCx,
frame: &FrameMeta,
pixels: &mut DecodedImage,
) -> Result<Vec<BBox>>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct NoRedaction;
#[async_trait]
impl PrivacyHook for NoRedaction {
fn name(&self) -> &str {
"none"
}
async fn redact(
&self,
_cx: &VisionCx,
_frame: &FrameMeta,
_pixels: &mut DecodedImage,
) -> Result<Vec<BBox>> {
Ok(Vec::new())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
pub enum RedactionMethod {
Fill,
Blur {
sigma: f32,
},
Pixelate {
block: u32,
},
ScaledBlur {
fraction: f32,
},
}
impl RedactionMethod {
pub const FACE_BLUR: Self = Self::ScaledBlur { fraction: 0.25 };
}
pub struct RedactorPrivacy {
redactor: Arc<dyn Redactor>,
method: RedactionMethod,
name: String,
hold: u64,
held: std::sync::Mutex<std::collections::HashMap<FrameSourceId, Vec<(u64, BBox)>>>,
}
const HOLD_GROWTH: f32 = 0.25;
impl std::fmt::Debug for RedactorPrivacy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RedactorPrivacy")
.field("name", &self.name)
.field("method", &self.method)
.field("hold", &self.hold)
.finish_non_exhaustive()
}
}
impl RedactorPrivacy {
pub fn new(redactor: Arc<dyn Redactor>, method: RedactionMethod) -> Self {
let name = format!("redactor:{}", redactor.class());
Self { redactor, method, name, hold: 0, held: std::sync::Mutex::default() }
}
pub fn with_hold(mut self, frames: u64) -> Self {
self.hold = frames;
self
}
#[cfg(any(feature = "onnx", feature = "onnx-dynamic"))]
pub fn blur_faces(fetcher: crate::ModelFetcher) -> Self {
Self::new(Arc::new(crate::FaceRedactor::on_device(fetcher)), RedactionMethod::FACE_BLUR)
.with_hold(2)
}
}
#[async_trait]
impl PrivacyHook for RedactorPrivacy {
fn name(&self) -> &str {
&self.name
}
async fn redact(
&self,
cx: &VisionCx,
frame: &FrameMeta,
pixels: &mut DecodedImage,
) -> Result<Vec<BBox>> {
let (w, h) = pixels.size();
let view = SentImage::new(
Digest::of(pixels.rgba()),
Arc::new(pixels.clone()),
TransformChain::new(w, h),
);
let found = self.redactor.find(cx, &view).await?;
let mut boxes = found.clone();
if self.hold > 0 {
let mut held = self.held.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let recent = held.entry(frame.source.clone()).or_default();
recent.retain(|(then, _)| frame.index > *then && frame.index - then <= self.hold);
for (then, bbox) in recent.iter() {
let age = (frame.index - then) as f32;
let grown = bbox
.expanded(HOLD_GROWTH * age * bbox.width().max(bbox.height()))
.clamped(w, h);
if !found.iter().any(|f| f.intersection(&grown).is_some()) {
boxes.push(grown);
}
}
recent.extend(found.iter().map(|bbox| (frame.index, *bbox)));
}
let mut redacted = Vec::with_capacity(boxes.len());
for bbox in boxes {
let padded = BBox::new(
bbox.x0 - REDACTION_MARGIN,
bbox.y0 - REDACTION_MARGIN,
bbox.x1 + REDACTION_MARGIN,
bbox.y1 + REDACTION_MARGIN,
);
match self.method {
RedactionMethod::Fill => {
ops::fill(pixels, &padded, Rgba([0, 0, 0, 255]));
}
RedactionMethod::Blur { sigma } => ops::blur(pixels, &padded, sigma),
RedactionMethod::Pixelate { block } => ops::pixelate(pixels, &padded, block.max(2)),
RedactionMethod::ScaledBlur { fraction } => {
let sigma = fraction * padded.width().max(padded.height());
ops::fast_blur(pixels, &padded, sigma);
}
}
redacted.push(padded);
}
Ok(redacted)
}
}
#[derive(Clone, Debug)]
pub struct RedactedFrame {
meta: FrameMeta,
pixels: Arc<DecodedImage>,
hook: String,
redacted: Vec<BBox>,
}
impl RedactedFrame {
pub fn meta(&self) -> &FrameMeta {
&self.meta
}
pub fn pixels(&self) -> &DecodedImage {
&self.pixels
}
pub(crate) fn shared_pixels(&self) -> Arc<DecodedImage> {
Arc::clone(&self.pixels)
}
pub fn hook(&self) -> &str {
&self.hook
}
pub fn redacted(&self) -> &[BBox] {
&self.redacted
}
}
#[derive(Clone)]
pub struct FramePrivacy {
hook: Arc<dyn PrivacyHook>,
}
impl std::fmt::Debug for FramePrivacy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FramePrivacy").field("hook", &self.hook.name()).finish()
}
}
impl FramePrivacy {
pub fn new(hook: Arc<dyn PrivacyHook>) -> Self {
Self { hook }
}
pub fn hook_name(&self) -> &str {
self.hook.name()
}
pub async fn apply(&self, cx: &VisionCx, frame: Frame) -> Result<RedactedFrame> {
let meta = frame.meta();
let shared = match frame.pixels {
FramePixels::Ephemeral(pixels) => pixels,
FramePixels::Stored(image) => {
return Err(VisionError::InvalidInput(format!(
"frame {} of `{}` is already stored as {}; a stored frame was redacted before its write",
meta.index, meta.source.0, image.digest
)));
}
};
let mut pixels = Arc::try_unwrap(shared).unwrap_or_else(|shared| (*shared).clone());
let redacted = self.hook.redact(cx, &meta, &mut pixels).await?;
Ok(RedactedFrame {
meta,
pixels: Arc::new(pixels),
hook: self.hook.name().to_string(),
redacted,
})
}
}