1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use std::collections::HashSet;
use std::sync::Arc;
use std::time::SystemTime;
use arc_swap::ArcSwapOption;
use tokio::sync::broadcast;
use tokio::time::MissedTickBehavior;
use crate::error::{Error, Result};
use crate::event::{Event, EventKind, ThresholdDirection};
use crate::session::{recompute_capture_rate, Session, WatcherEntry};
use crate::stream::EventStream;
use visual_cortex_capture::{Frame, FrameView, PxRect, Rate, Region};
use visual_cortex_vision::{
Detector, DetectorError, DetectorOutput, FrameDiff, OcrDetector, OcrEngine, Preprocessor,
TemplateMatcher, TextSpan,
};
const DEGRADED_THRESHOLD: u32 = 5;
pub(crate) enum Mode {
Change,
EveryMatch,
Threshold(Box<dyn Fn(f64) -> bool + Send + 'static>),
Template { threshold: f32 },
}
/// Configures one watcher. Created via `Session::watch`; consumed by `subscribe`.
/// OCR configuration captured by the sugar methods; the detector itself is
/// built at `subscribe()` so `.span_filter()` composes in any chain order.
enum PendingOcr {
Text(Box<dyn OcrEngine>),
Spans(Box<dyn OcrEngine>),
Number(Box<dyn OcrEngine>, NumberParser),
}
type SpanFilter = Box<dyn Fn(&TextSpan) -> bool + Send + 'static>;
type NumberParser = Box<dyn Fn(&str) -> Option<f64> + Send + 'static>;
pub struct WatcherBuilder<'s> {
session: &'s Session,
name: String,
region: Region,
rate: Rate,
frame_diff: bool,
gates: Vec<Box<dyn Detector>>,
preprocessors: Vec<Box<dyn Preprocessor>>,
detector: Option<Box<dyn Detector>>,
pending_ocr: Option<PendingOcr>,
span_filters: Vec<SpanFilter>,
mode: Mode,
template_error: Option<Error>,
}
impl<'s> WatcherBuilder<'s> {
pub(crate) fn new(session: &'s Session, name: &str) -> Self {
Self {
session,
name: name.to_string(),
region: Region::Full,
rate: Rate::hz(1.0),
frame_diff: true,
gates: Vec::new(),
preprocessors: Vec::new(),
detector: None,
pending_ocr: None,
span_filters: Vec::new(),
mode: Mode::Change,
template_error: None,
}
}
pub fn region(mut self, region: Region) -> Self {
self.region = region;
self
}
pub fn rate(mut self, rate: Rate) -> Self {
self.rate = rate;
self
}
/// The implicit pixels-changed gate. On by default; disable for detectors
/// that must run even when the region is static.
pub fn frame_diff(mut self, enabled: bool) -> Self {
self.frame_diff = enabled;
self
}
/// Add a gate: a boolean detector that must report `Bool(true)` for the
/// main detector to run this tick. Gates run in registration order.
pub fn gate(mut self, gate: impl Detector) -> Self {
self.gates.push(Box::new(gate));
self
}
/// Add a preprocessor: transforms the cropped view before the implicit
/// frame-diff gate, the gates, and the detector. Chainable; run in
/// registration order (each stage sees the previous stage's output).
/// A static preprocessor output holds the frame-diff gate closed even
/// while raw input churns — that synergy is the point (see
/// `StabilityMask`).
pub fn preprocess(mut self, preprocessor: impl Preprocessor) -> Self {
self.preprocessors.push(Box::new(preprocessor));
self
}
pub fn detector(mut self, detector: impl Detector) -> Self {
self.detector = Some(Box::new(detector));
self
}
/// Default mode: emit `Changed` when the detector output transitions.
pub fn on_change(mut self) -> Self {
self.mode = Mode::Change;
self
}
/// Emit `Matched` on every tick where the detector matches.
pub fn on_every_match(mut self) -> Self {
self.mode = Mode::EveryMatch;
self
}
/// Emit `ThresholdCrossed` when `predicate(numeric_output)` flips.
pub fn on_threshold(mut self, predicate: impl Fn(f64) -> bool + Send + 'static) -> Self {
self.mode = Mode::Threshold(Box::new(predicate));
self
}
/// Watch for a PNG template. Emits `TemplateAppeared` when the best match
/// score reaches `threshold` (0.0..=1.0) and `TemplateVanished` when it
/// falls back below. Sets both the detector and the emission mode; like
/// all builder configuration, the last call wins.
pub fn template(mut self, png_bytes: &[u8], threshold: f32) -> Self {
match TemplateMatcher::from_png_bytes(png_bytes) {
Ok(matcher) => {
self.detector = Some(Box::new(matcher));
self.mode = Mode::Template { threshold };
}
Err(e) => {
self.template_error =
Some(Error::InvalidTemplate(self.name.clone(), e.to_string()));
}
}
self
}
/// OCR the region and emit text transitions (`Changed` with
/// `DetectorOutput::Text`/`None`). "Text appeared" is the
/// `None -> Text(..)` transition. Sets the detector only; the emission
/// mode stays chainable.
pub fn ocr_text(mut self, engine: impl OcrEngine) -> Self {
self.pending_ocr = Some(PendingOcr::Text(Box::new(engine)));
self
}
/// OCR the region and emit span transitions (`Changed` with
/// `DetectorOutput::Spans`/`None`), preserving each span's bounding box
/// and confidence for layout-aware consumers. Change detection compares
/// span texts only, so OCR geometry jitter does not fire events. Sets the
/// detector only; the emission mode stays chainable.
pub fn ocr_spans(mut self, engine: impl OcrEngine) -> Self {
self.pending_ocr = Some(PendingOcr::Spans(Box::new(engine)));
self
}
/// OCR the region and parse a number out of the text (see
/// [`patterns::number`](visual_cortex_vision::patterns::number)). Pair with
/// `.on_threshold(..)` for HP-bar-style watchers.
pub fn ocr(
mut self,
engine: impl OcrEngine,
pattern: impl Fn(&str) -> Option<f64> + Send + 'static,
) -> Self {
self.pending_ocr = Some(PendingOcr::Number(Box::new(engine), Box::new(pattern)));
self
}
/// Filter OCR spans (`true` = keep) BEFORE change detection — filtered
/// spans can never fire `Changed` events, so noisy UI text (console
/// button prompts, chat zones) is suppressed at the root rather than
/// post-hoc. Composable; applies to whichever `.ocr*` sugar is used on
/// this watcher (any chain order). Stock filters:
/// [`filters`](visual_cortex_vision::filters).
pub fn span_filter(mut self, filter: impl Fn(&TextSpan) -> bool + Send + 'static) -> Self {
self.span_filters.push(Box::new(filter));
self
}
/// Register the watcher and return its event stream.
pub fn subscribe(mut self) -> Result<EventStream> {
// Hand the watcher name to stages with debug output.
for pp in self.preprocessors.iter_mut() {
pp.set_label(&self.name);
}
if let Some(e) = self.template_error {
return Err(e);
}
let detector = match (self.detector, self.pending_ocr) {
(Some(det), None) => {
if !self.span_filters.is_empty() {
tracing::warn!(
watcher = %self.name,
"span_filter() has no effect without an .ocr*() sugar; ignoring"
);
}
det
}
(None, Some(pending)) => {
let mut det = match pending {
PendingOcr::Text(engine) => OcrDetector::text(engine),
PendingOcr::Spans(engine) => OcrDetector::spans(engine),
PendingOcr::Number(engine, parser) => OcrDetector::number(engine, parser),
};
for f in self.span_filters {
det = det.with_span_filter(f);
}
Box::new(det) as Box<dyn Detector>
}
(Some(_), Some(_)) => {
// Last-call-wins is the builder convention elsewhere, but
// detector-vs-ocr is ambiguous; make it a hard error.
return Err(Error::MissingDetector(format!(
"{}: both .detector() and an .ocr*() sugar were configured; pick one",
self.name
)));
}
(None, None) => return Err(Error::MissingDetector(self.name.clone())),
};
// Atomically reserve the name so duplicate watchers fail fast, storing
// the rate now so a concurrent recompute already sees this watcher.
{
let mut watchers = self.session.inner.watchers.lock().unwrap();
if watchers.contains_key(&self.name) {
return Err(Error::DuplicateWatcher(self.name));
}
watchers.insert(
self.name.clone(),
WatcherEntry {
rate: self.rate,
task: None,
},
);
}
let rx = self.session.inner.events.subscribe();
let runtime = WatcherRuntime {
name: Arc::from(self.name.as_str()),
region: self.region,
rate: self.rate,
frame_diff: self.frame_diff,
preprocessors: self.preprocessors,
gates: self.gates,
detector: Some(detector),
mode: self.mode,
};
let task = tokio::spawn(watcher_loop(
runtime,
self.session.inner.slot.clone(),
self.session.inner.events.clone(),
));
self.session
.inner
.watchers
.lock()
.unwrap()
.get_mut(&self.name)
.expect("entry reserved above")
.task = Some(task);
recompute_capture_rate(&self.session.inner);
Ok(EventStream::new(rx, HashSet::from([self.name])))
}
}
struct WatcherRuntime {
name: Arc<str>,
region: Region,
rate: Rate,
frame_diff: bool,
preprocessors: Vec<Box<dyn Preprocessor>>,
gates: Vec<Box<dyn Detector>>,
detector: Option<Box<dyn Detector>>,
mode: Mode,
}
async fn watcher_loop(
mut w: WatcherRuntime,
slot: Arc<ArcSwapOption<Frame>>,
events: broadcast::Sender<Event>,
) {
let mut interval = tokio::time::interval(w.rate.period());
interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut diff_gate = w.frame_diff.then(FrameDiff::new);
let mut last_output: Option<DetectorOutput> = None;
let mut inside_threshold: Option<bool> = None;
let mut consecutive_errors: u32 = 0;
loop {
interval.tick().await;
let Some(frame) = slot.load_full() else {
continue;
};
let rect = match w.region.resolve(frame.width(), frame.height()) {
Ok(rect) => rect,
Err(e) => {
tracing::warn!(watcher = %w.name, "region does not fit frame: {e}");
continue;
}
};
// Preprocessor stage: each transforms the previous stage's output;
// all later stages (diff gate, gates, detector) see the final frame.
let mut frame = frame;
let mut rect = rect;
let mut preprocess_failed = false;
for pp in w.preprocessors.iter_mut() {
let next = {
let v = match frame.view(rect) {
Ok(v) => v,
Err(e) => {
tracing::warn!(watcher = %w.name, "preprocess view failed: {e}");
preprocess_failed = true;
break;
}
};
match pp.process(&v) {
Ok(n) => n,
Err(e) => {
tracing::warn!(watcher = %w.name, "preprocessor error, skipping tick: {e}");
preprocess_failed = true;
break;
}
}
};
rect = PxRect {
x: 0,
y: 0,
w: next.width(),
h: next.height(),
};
frame = next;
}
if preprocess_failed {
continue;
}
let view = match frame.view(rect) {
Ok(view) => view,
Err(e) => {
tracing::warn!(watcher = %w.name, "crop failed: {e}");
continue;
}
};
if let Some(gate) = &mut diff_gate {
if matches!(gate.evaluate(&view), Ok(DetectorOutput::Bool(false))) {
continue;
}
}
if !gates_pass(&mut w.gates, &view, &w.name) {
continue;
}
let result = if w.detector.as_ref().is_some_and(|d| d.is_heavy()) {
// Move the detector and an owned frame handle onto the blocking
// pool; CPU-bound inference must not stall the async scheduler.
let mut detector = w.detector.take().expect("detector present");
let frame = frame.clone();
match tokio::task::spawn_blocking(move || {
// AssertUnwindSafe: a caught panic may leave the detector
// logically inconsistent; we accept that — subsequent
// failures count toward WatcherDegraded.
let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let view = frame.view(rect).expect("rect was validated for this frame");
detector.evaluate(&view)
}))
.unwrap_or_else(|_| Err(DetectorError::Other("detector panicked".to_string())));
(detector, out)
})
.await
{
Ok((detector, out)) => {
w.detector = Some(detector);
out
}
Err(join_err) => {
// Unreachable in practice: detector panics are caught above,
// and blocking tasks are not cancelled once started. If it
// does happen the detector is lost, so the watcher cannot
// continue; signal subscribers and end the loop. (The
// registry entry remains until unsubscribe/session drop.)
tracing::error!(watcher = %w.name, "blocking task failed: {join_err}");
send(
&events,
&w.name,
EventKind::WatcherDegraded {
consecutive_errors: consecutive_errors + 1,
},
);
// Terminal marker: without it, subscribers of only this
// watcher would await a stream that never yields again.
send(&events, &w.name, EventKind::WatcherStopped);
return;
}
}
} else {
w.detector
.as_mut()
.expect("detector present")
.evaluate(&view)
};
match result {
Ok(output) => {
consecutive_errors = 0;
emit(
&w.mode,
&w.name,
&events,
output,
&mut last_output,
&mut inside_threshold,
);
}
Err(e) => {
consecutive_errors += 1;
tracing::warn!(
watcher = %w.name,
"detector error ({consecutive_errors} consecutive): {e}"
);
if consecutive_errors == DEGRADED_THRESHOLD {
send(
&events,
&w.name,
EventKind::WatcherDegraded { consecutive_errors },
);
}
}
}
}
}
fn gates_pass(gates: &mut [Box<dyn Detector>], view: &FrameView<'_>, name: &Arc<str>) -> bool {
for gate in gates.iter_mut() {
match gate.evaluate(view) {
Ok(DetectorOutput::Bool(true)) => {}
Ok(_) => return false, // Bool(false) or any non-boolean output closes the gate
Err(e) => {
tracing::warn!(watcher = %name, "gate error, skipping tick: {e}");
return false;
}
}
}
true
}
fn send(events: &broadcast::Sender<Event>, name: &Arc<str>, kind: EventKind) {
let _ = events.send(Event {
watcher: name.clone(),
timestamp: SystemTime::now(),
kind,
});
}
fn emit(
mode: &Mode,
name: &Arc<str>,
events: &broadcast::Sender<Event>,
output: DetectorOutput,
last_output: &mut Option<DetectorOutput>,
inside_threshold: &mut Option<bool>,
) {
match mode {
Mode::EveryMatch => {
let matched = !matches!(output, DetectorOutput::None | DetectorOutput::Bool(false));
if matched {
send(events, name, EventKind::Matched { output });
}
}
Mode::Change => {
if last_output.as_ref() != Some(&output) {
send(
events,
name,
EventKind::Changed {
old: last_output.clone(),
new: output.clone(),
},
);
}
*last_output = Some(output);
}
Mode::Threshold(predicate) => {
let Some(value) = output.as_number() else {
return;
};
let inside = predicate(value);
match *inside_threshold {
// First observation: fire only if we start inside the threshold —
// "HP is already low" is worth knowing; "HP is fine" is not.
None if inside => send(
events,
name,
EventKind::ThresholdCrossed {
value,
direction: ThresholdDirection::Entered,
},
),
Some(prev) if prev != inside => {
let direction = if inside {
ThresholdDirection::Entered
} else {
ThresholdDirection::Exited
};
send(
events,
name,
EventKind::ThresholdCrossed { value, direction },
);
}
_ => {}
}
*inside_threshold = Some(inside);
}
Mode::Template { threshold } => {
let Some(score) = output.as_number() else {
return;
};
let present = score >= *threshold as f64;
match *inside_threshold {
// First observation: only an already-visible template is news.
None if present => send(
events,
name,
EventKind::TemplateAppeared {
score: score as f32,
},
),
Some(prev) if prev != present => {
if present {
send(
events,
name,
EventKind::TemplateAppeared {
score: score as f32,
},
);
} else {
send(events, name, EventKind::TemplateVanished);
}
}
_ => {}
}
*inside_threshold = Some(present);
}
}
}