1use std::sync::Arc;
8use std::time::Duration as StdDuration;
9
10use adk_artifact::{ArtifactService, SaveRequest};
11use adk_core::{ArtifactLocator, ImageEvidence, Part};
12use async_trait::async_trait;
13use chrono::{DateTime, Duration, FixedOffset, Utc};
14use serde_json::{Value, json};
15use tokio::sync::RwLock;
16use tokio::task::JoinHandle;
17
18use super::facts::{
19 CameraFacts, CameraFrame, EscalationFacts, Finding, GovernorFacts, GovernorStep,
20 GovernorStepKind, HeldFrame, Ingest, Measurement, Overlay, StreamState, TrackFacts, TrackPhase,
21 WatchFacts, ZoneFacts,
22};
23use super::hub::{CameraSource, Cameras};
24use crate::error::{Result, SurfaceError};
25
26const PARTS: [(u64, [f64; 4]); 4] = [
28 (45, [330.0, 300.0, 630.0, 530.0]),
29 (43, [840.0, 400.0, 1140.0, 630.0]),
30 (42, [1290.0, 250.0, 1590.0, 480.0]),
31 (41, [1720.0, 470.0, 1920.0, 700.0]),
32];
33const TEAR: [f64; 4] = [922.0, 490.0, 1024.0, 532.0];
34const FIDUCIAL: [f64; 4] = [40.0, 660.0, 285.0, 905.0];
35const ZONE: [f64; 4] = [760.0, 170.0, 1560.0, 910.0];
36const BENCH_PERSON: [f64; 4] = [200.0, 150.0, 720.0, 720.0];
37const STEP: f64 = 46.0;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum CameraBoard {
43 Live,
45 SteppedDown,
47 QuotaExhausted,
49 SourceLost,
51 SwitchedOff,
53 Later,
55}
56
57impl CameraBoard {
58 pub fn now(self, day: DateTime<FixedOffset>) -> DateTime<Utc> {
60 let at = |h: i64, m: i64, s: i64| {
61 (day + Duration::hours(h) + Duration::minutes(m) + Duration::seconds(s)).to_utc()
62 };
63 match self {
64 Self::Live => at(10, 41, 12),
65 Self::SteppedDown => at(14, 40, 15),
66 Self::QuotaExhausted => at(15, 20, 0),
67 Self::SourceLost => at(10, 42, 51),
68 Self::SwitchedOff => at(11, 6, 0),
69 Self::Later => at(10, 43, 20),
70 }
71 }
72
73 pub fn frame_at(self, day: DateTime<FixedOffset>) -> DateTime<Utc> {
75 let at = |h: i64, m: i64, s: i64| {
76 (day + Duration::hours(h) + Duration::minutes(m) + Duration::seconds(s)).to_utc()
77 };
78 match self {
79 Self::Live | Self::SwitchedOff => at(10, 41, 9),
80 Self::SteppedDown => at(14, 40, 12),
81 Self::QuotaExhausted => at(15, 12, 3),
82 Self::SourceLost => at(10, 42, 7),
83 Self::Later => at(10, 43, 18),
84 }
85 }
86
87 fn tracks(self) -> [u64; 4] {
89 match self {
90 Self::SteppedDown | Self::QuotaExhausted => [91, 90, 89, 88],
91 Self::Later => [49, 48, 47, 46],
92 Self::Live | Self::SourceLost | Self::SwitchedOff => [45, 43, 42, 41],
93 }
94 }
95}
96
97pub struct ScriptedCameras {
117 app: String,
118 user: String,
119 cameras: RwLock<Vec<CameraFacts>>,
120 artifacts: Option<Arc<dyn ArtifactService>>,
121 log: RwLock<Vec<String>>,
123}
124
125impl std::fmt::Debug for ScriptedCameras {
126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 f.debug_struct("ScriptedCameras").field("app", &self.app).finish_non_exhaustive()
128 }
129}
130
131impl ScriptedCameras {
132 pub fn new(app: impl Into<String>, user: impl Into<String>) -> Self {
134 Self {
135 app: app.into(),
136 user: user.into(),
137 cameras: RwLock::new(Vec::new()),
138 artifacts: None,
139 log: RwLock::new(Vec::new()),
140 }
141 }
142
143 pub fn boards(
146 app: impl Into<String>,
147 user: impl Into<String>,
148 session: &str,
149 board: CameraBoard,
150 day: DateTime<FixedOffset>,
151 ) -> Self {
152 let source = Self::new(app, user);
153 let cameras = vec![
154 line_2(session, board, day),
155 line_3(session, day),
156 packing_bench(session, day),
157 this_computer(session),
158 ];
159 Self { cameras: RwLock::new(cameras), ..source }
160 }
161
162 #[must_use]
164 pub fn artifacts(mut self, artifacts: Arc<dyn ArtifactService>) -> Self {
165 self.artifacts = Some(artifacts);
166 self
167 }
168
169 pub async fn set(&self, facts: CameraFacts) {
171 let mut cameras = self.cameras.write().await;
172 match cameras.iter_mut().find(|camera| camera.id == facts.id) {
173 Some(camera) => *camera = facts,
174 None => cameras.push(facts),
175 }
176 }
177
178 pub async fn camera(&self, id: &str) -> Option<CameraFacts> {
180 self.cameras.read().await.iter().find(|camera| camera.id == id).cloned()
181 }
182
183 pub async fn log(&self) -> Vec<String> {
185 self.log.read().await.clone()
186 }
187
188 pub fn frames(
191 camera: &str,
192 board: CameraBoard,
193 bytes: &[u8],
194 mime_type: &str,
195 at: DateTime<Utc>,
196 ) -> Vec<CameraFrame> {
197 (0..5)
198 .rev()
199 .map(|back| {
200 let shift = STEP * f64::from(back);
201 let overlays = overlays(camera, board, shift, back == 0);
202 CameraFrame::new(
203 bytes.to_vec(),
204 mime_type,
205 1920,
206 1080,
207 at - Duration::milliseconds(200 * i64::from(back)),
208 )
209 .with_overlays(overlays)
210 .with_latency_ms(match board {
211 CameraBoard::SteppedDown | CameraBoard::QuotaExhausted => 200,
212 _ => 100,
213 })
214 })
215 .collect()
216 }
217
218 pub async fn show(cameras: &Cameras, camera: &str, frames: Vec<CameraFrame>) {
220 for frame in frames {
221 cameras.offer(camera, frame).await;
222 }
223 }
224
225 pub fn play(
229 cameras: Cameras,
230 camera: impl Into<String>,
231 board: CameraBoard,
232 picture: Vec<u8>,
233 mime_type: impl Into<String>,
234 interval: StdDuration,
235 ) -> JoinHandle<()> {
236 let camera = camera.into();
237 let mime_type = mime_type.into();
238 tokio::spawn(async move {
239 let mut ticks = tokio::time::interval(interval);
240 loop {
241 ticks.tick().await;
242 let frame =
243 CameraFrame::new(picture.clone(), mime_type.clone(), 1920, 1080, Utc::now())
244 .with_overlays(overlays(&camera, board, 0.0, true))
245 .with_latency_ms(100);
246 cameras.offer(&camera, frame).await;
247 }
248 })
249 }
250}
251
252#[async_trait]
253impl CameraSource for ScriptedCameras {
254 async fn cameras(&self) -> Result<Vec<CameraFacts>> {
255 Ok(self.cameras.read().await.clone())
256 }
257
258 async fn retry(&self, camera: &str) -> Result<()> {
259 self.log.write().await.push(format!("retry {camera}"));
260 Ok(())
261 }
262
263 async fn save_zone(&self, camera: &str, zone: &ZoneFacts) -> Result<()> {
264 let mut cameras = self.cameras.write().await;
265 let facts = cameras
266 .iter_mut()
267 .find(|facts| facts.id == camera)
268 .ok_or_else(|| SurfaceError::not_found(format!("camera '{camera}'")))?;
269 let entry = facts
270 .zones
271 .iter_mut()
272 .find(|candidate| candidate.id == zone.id)
273 .ok_or_else(|| SurfaceError::not_found(format!("zone '{}'", zone.id)))?;
274 *entry = zone.clone();
275 self.log.write().await.push(format!("zone {camera}/{} {:?}", zone.id, zone.corners));
276 Ok(())
277 }
278
279 async fn keep_frame(&self, camera: &CameraFacts, frame: &HeldFrame) -> Result<ImageEvidence> {
280 let artifacts = self
281 .artifacts
282 .as_ref()
283 .ok_or_else(|| SurfaceError::unsupported("keeping a camera's frames"))?;
284 let picture = &frame.frame;
285 let people: Vec<[u32; 4]> = picture
288 .overlays
289 .iter()
290 .filter(|overlay| {
291 overlay.blurred || overlay.label == "person" || overlay.label == "face"
292 })
293 .filter_map(|overlay| overlay.bbox)
294 .map(|[x0, y0, x1, y1]| {
295 let clamp = |value: f64, max: u32| (value.max(0.0) as u32).min(max);
296 [
297 clamp(x0.floor(), picture.width),
298 clamp(y0.floor(), picture.height),
299 clamp(x1.ceil(), picture.width),
300 clamp(y1.ceil(), picture.height),
301 ]
302 })
303 .filter(|[x0, y0, x1, y1]| x0 < x1 && y0 < y1)
304 .collect();
305 let (bytes, mime_type) = if people.is_empty() {
306 (picture.bytes.clone(), picture.mime_type.clone())
307 } else if picture.mime_type == "image/png" {
308 let change =
309 crate::evidence::ImageChange { image: 0, crop: None, cover: people.clone() };
310 let (covered, _, _) = crate::evidence::changed_png(&picture.bytes, &change)
311 .map_err(SurfaceError::Invalid)?;
312 (covered, "image/png".to_string())
313 } else {
314 return Err(SurfaceError::Invalid(
315 "this frame has people in it and is not a PNG this source can cover; it is not kept"
316 .into(),
317 ));
318 };
319 let digest = crate::evidence::digest_of(&bytes);
320 let extension = match mime_type.as_str() {
321 "image/jpeg" => "jpeg",
322 "image/webp" => "webp",
323 _ => "png",
324 };
325 let hex = digest.trim_start_matches("sha256:");
326 let file_name = format!("vision-{hex}.{extension}");
327 let saved = artifacts
328 .save(SaveRequest {
329 app_name: self.app.clone(),
330 user_id: self.user.clone(),
331 session_id: camera.session.clone(),
332 file_name: file_name.clone(),
333 part: Part::InlineData {
334 mime_type: mime_type.clone(),
335 data: bytes,
336 uri: None,
337 annotations: None,
338 },
339 version: None,
340 })
341 .await?;
342 let regions: Vec<Value> = people
345 .iter()
346 .map(|[x0, y0, x1, y1]| {
347 json!({
348 "image": digest,
349 "shape": { "kind": "box", "x0": x0, "y0": y0, "x1": x1, "y1": y1 },
350 "label": "person",
351 "origin": { "backend": "camera", "frame": "sourcePixels" },
352 })
353 })
354 .collect();
355 Ok(ImageEvidence::new(
356 digest.clone(),
357 ArtifactLocator::new(
358 self.app.clone(),
359 self.user.clone(),
360 camera.session.clone(),
361 file_name,
362 saved.version,
363 ),
364 mime_type,
365 picture.width,
366 picture.height,
367 )
368 .with_regions(json!({
369 "image": digest,
370 "width": picture.width,
371 "height": picture.height,
372 "regions": regions,
373 }))
374 .with_caption(format!("{} at {}", camera.name, picture.at.format("%H:%M:%S"))))
375 }
376}
377
378fn at(day: DateTime<FixedOffset>, h: i64, m: i64) -> DateTime<Utc> {
383 (day + Duration::hours(h) + Duration::minutes(m)).to_utc()
384}
385
386fn line_2(session: &str, board: CameraBoard, day: DateTime<FixedOffset>) -> CameraFacts {
387 let midnight = (day + Duration::days(1)).to_utc();
388 let [first, second, third, fourth] = board.tracks();
389 let part =
390 |id: u64, phase: TrackPhase| TrackFacts { id, label: "part".into(), phase, finding: None };
391 let escalation = EscalationFacts {
392 backend: "sam-3.1".into(),
393 last_minute: 2,
394 max_per_minute: 6,
395 today: 14,
396 cost_today_micros: 140_000,
397 stopped_at: None,
398 };
399 let mut governor = GovernorFacts::new(5.0, 300_000, midnight)
400 .with_escalation(escalation.clone())
401 .with_frames_today(61_240);
402 let looked_less = GovernorStep {
403 at: at(day, 14, 2),
404 kind: GovernorStepKind::LookLessOften { from: 5.0, to: 2.0 },
405 used: Some(0.9),
406 };
407 let stopped_asking =
408 GovernorStep { at: at(day, 14, 31), kind: GovernorStepKind::StopAsking, used: Some(0.95) };
409 let mut state = StreamState::Live;
410 let mut tracks = vec![
411 TrackFacts {
412 finding: Some(Finding { label: "seal tear".into(), score: 0.91, frames: 5 }),
413 ..part(second, TrackPhase::InZone)
414 },
415 part(third, TrackPhase::InZone),
416 part(first, TrackPhase::Entering),
417 part(fourth, TrackPhase::Leaving),
418 ];
419 match board {
420 CameraBoard::Live | CameraBoard::Later => {}
421 CameraBoard::SteppedDown | CameraBoard::QuotaExhausted => {
422 governor = governor
423 .with_rate(2.0)
424 .with_frames_today(287_400)
425 .with_step(looked_less)
426 .with_step(stopped_asking);
427 governor.escalation = Some(EscalationFacts {
428 last_minute: 0,
429 stopped_at: Some(at(day, 14, 31)),
430 ..escalation
431 });
432 tracks = vec![
433 part(second, TrackPhase::InZone),
434 part(third, TrackPhase::InZone),
435 part(first, TrackPhase::Entering),
436 part(fourth, TrackPhase::Leaving),
437 ];
438 if board == CameraBoard::QuotaExhausted {
439 governor = governor.with_frames_today(300_000).with_step(GovernorStep {
440 at: at(day, 15, 12),
441 kind: GovernorStepKind::Pause,
442 used: Some(1.0),
443 });
444 state = StreamState::Paused { since: at(day, 15, 12) };
445 tracks.clear();
446 }
447 }
448 CameraBoard::SourceLost => {
449 let since = board.frame_at(day);
450 governor = governor.with_frames_today(64_180);
451 if let Some(escalation) = governor.escalation.as_mut() {
452 escalation.last_minute = 0;
453 }
454 state = StreamState::Lost {
455 since,
456 retry_at: board.now(day) + Duration::seconds(8),
457 attempt: 3,
458 error: "connection refused · rtsp://[credentials hidden]@10.0.4.21:554/stream1"
459 .into(),
460 };
461 tracks.clear();
462 }
463 CameraBoard::SwitchedOff => {
464 governor = governor.with_frames_today(64_400);
465 if let Some(escalation) = governor.escalation.as_mut() {
466 escalation.last_minute = 0;
467 }
468 tracks.clear();
469 }
470 }
471 CameraFacts::new("line-2", "Line 2 camera", "inspector", session)
472 .with_place("line 2")
473 .passing("parts")
474 .with_ingest(Ingest::rtsp(1920, 1080, "the line 2 server"))
475 .with_state(state)
476 .with_governor(governor)
477 .with_tracks(tracks)
478 .with_watches(vec![WatchFacts {
479 id: "seal-tear".into(),
480 name: "Seal tear".into(),
481 label: "seal tear".into(),
482 min_score: 0.8,
483 frames: 3,
484 zone: Some("inspection-window".into()),
485 cooldown_secs: 30,
486 woke_today: 3,
487 wakes_for: Some("a defect".into()),
488 }])
489 .with_zones(vec![ZoneFacts {
490 id: "inspection-window".into(),
491 name: "Inspection window".into(),
492 corners: ZONE,
493 }])
494}
495
496fn line_3(session: &str, day: DateTime<FixedOffset>) -> CameraFacts {
497 let midnight = (day + Duration::days(1)).to_utc();
498 let governor = GovernorFacts::new(5.0, 300_000, midnight)
499 .with_escalation(EscalationFacts {
500 backend: "sam-3.1".into(),
501 last_minute: 0,
502 max_per_minute: 6,
503 today: 31,
504 cost_today_micros: 310_000,
505 stopped_at: Some(at(day, 13, 50)),
506 })
507 .with_rate(2.0)
508 .with_frames_today(287_400)
509 .with_step(GovernorStep {
510 at: at(day, 13, 20),
511 kind: GovernorStepKind::LookLessOften { from: 5.0, to: 2.0 },
512 used: Some(0.9),
513 })
514 .with_step(GovernorStep {
515 at: at(day, 13, 50),
516 kind: GovernorStepKind::StopAsking,
517 used: Some(0.95),
518 });
519 CameraFacts::new("line-3", "Line 3 camera", "inspector", session)
520 .with_place("line 3")
521 .passing("parts")
522 .with_ingest(Ingest::rtsp(1920, 1080, "the line 3 server"))
523 .with_governor(governor)
524 .with_watches(vec![WatchFacts {
525 id: "seal-tear-3".into(),
526 name: "Seal tear".into(),
527 label: "seal tear".into(),
528 min_score: 0.8,
529 frames: 3,
530 zone: None,
531 cooldown_secs: 30,
532 woke_today: 0,
533 wakes_for: Some("a defect".into()),
534 }])
535}
536
537fn packing_bench(session: &str, day: DateTime<FixedOffset>) -> CameraFacts {
538 let midnight = (day + Duration::days(1)).to_utc();
539 CameraFacts::new("packing-bench", "Packing bench", "inspector", session)
540 .with_place("the packing bench")
541 .with_ingest(Ingest::rtsp(1920, 1080, "the packing server"))
542 .with_governor(GovernorFacts::new(1.0, 50_000, midnight).with_frames_today(9_800))
543}
544
545fn this_computer(session: &str) -> CameraFacts {
546 CameraFacts::new("this-computer", "This computer's camera", "inspector", session)
547 .with_place("this computer")
548 .with_ingest(Ingest::this_computer(1280, 720))
549 .with_governor(GovernorFacts::new(1.0, 0, Utc::now()))
550 .from("from the voice screen")
551 .switched(false)
552}
553
554fn overlays(camera: &str, board: CameraBoard, shift: f64, newest: bool) -> Vec<Overlay> {
557 let back = |[x0, y0, x1, y1]: [f64; 4]| [x0 - shift, y0, (x1 - shift).min(1920.0), y1];
558 match camera {
559 "packing-bench" => vec![Overlay::boxed("person", BENCH_PERSON).blurred()],
560 "line-2" | "line-3" => {
561 let tracks = if camera == "line-3" { [45, 43, 42, 41] } else { board.tracks() };
562 let mut overlays: Vec<Overlay> = PARTS
563 .iter()
564 .zip(tracks)
565 .map(|((_, bbox), track)| {
566 Overlay::boxed("part", back(*bbox)).on_track(track).scored(0.96)
567 })
568 .collect();
569 if camera == "line-2"
570 && matches!(
571 board,
572 CameraBoard::Live | CameraBoard::SourceLost | CameraBoard::SwitchedOff
573 )
574 && newest
575 {
576 let track = tracks[1];
577 overlays.push(
578 Overlay { bbox: None, ..Overlay::boxed("seal", [0.0; 4]) }
579 .on_track(track)
580 .outlined(circle(990.0, 515.0, 84.0)),
581 );
582 overlays.push(
583 Overlay::boxed("seal tear", TEAR)
584 .on_track(track)
585 .scored(0.91)
586 .for_frames(5)
587 .outlined(vec![
588 [926.0, 494.0],
589 [950.0, 502.0],
590 [962.0, 494.0],
591 [979.0, 505.0],
592 [995.0, 498.0],
593 [1010.0, 508.0],
594 [1020.0, 508.0],
595 [1018.0, 518.0],
596 [1000.0, 532.0],
597 [958.0, 532.0],
598 [948.0, 512.0],
599 [930.0, 504.0],
600 ])
601 .measured(Measurement {
602 from: [930.0, 498.0],
603 to: [1016.0, 512.0],
604 millimetres: 14.3,
605 }),
606 );
607 }
608 if camera == "line-2" {
609 overlays.push(Overlay::boxed("fiducial", FIDUCIAL));
610 }
611 overlays
612 }
613 _ => Vec::new(),
614 }
615}
616
617fn circle(cx: f64, cy: f64, r: f64) -> Vec<[f64; 2]> {
619 (0..48)
620 .map(|step| {
621 let angle = f64::from(step) * std::f64::consts::TAU / 48.0;
622 [(cx + r * angle.cos()).round(), (cy + r * angle.sin()).round()]
623 })
624 .collect()
625}