forgewright 0.2.0

Standalone UI automation — CDP for browsers, UIA for Windows desktop apps
Documentation
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
//! CPU-only tile hash compression using FNV-1a.
//!
//! Provides the same tile-hash delta compression as the CUDA pipeline,
//! but runs entirely on the CPU. Used by ForgeWright's VisionBridge
//! when imported with `default-features = false`.

use crate::inlined_types::{CompressedFrame, Frame, TileDescriptor};

/// FNV-1a offset basis.
const FNV_OFFSET: u64 = 0xcbf29ce484222325;
/// FNV-1a prime.
const FNV_PRIME: u64 = 0x100000001b3;

/// Hash a single tile's pixel data using FNV-1a.
///
/// Iterates over every BGRA byte in the tile region defined by
/// `(col * tile_size, row * tile_size)` with dimensions `tile_size × tile_size`,
/// clamped to frame bounds for edge tiles.
pub fn hash_tile(frame: &Frame, col: u32, row: u32, tile_size: u32) -> u64 {
    let mut hash: u64 = FNV_OFFSET;
    let x0 = (col * tile_size) as usize;
    let y0 = (row * tile_size) as usize;
    let w = frame.width as usize;
    let h = frame.height as usize;

    for dy in 0..tile_size as usize {
        let y = y0 + dy;
        if y >= h {
            break;
        }
        for dx in 0..tile_size as usize {
            let x = x0 + dx;
            if x >= w {
                break;
            }
            let px = (y * w + x) * 4;
            for c in 0..4 {
                hash ^= frame.data[px + c] as u64;
                hash = hash.wrapping_mul(FNV_PRIME);
            }
        }
    }
    hash
}

/// Compress a frame into a `CompressedFrame` using CPU-side FNV-1a tile hashing.
///
/// - Divides the frame into `tile_size x tile_size` tiles.
/// - Hashes each tile with FNV-1a.
/// - Compares against `prev_hashes` for delta detection (first frame = all changed).
/// - Extracts per-tile features (mean color, edge density, likely_text) for changed tiles only.
/// - Updates `prev_hashes` with the current frame's hashes.
pub fn cpu_compress_frame(
    frame: &Frame,
    prev_hashes: &mut Option<Vec<u64>>,
    tile_size: u32,
) -> CompressedFrame {
    let cols = (frame.width + tile_size - 1) / tile_size;
    let rows = (frame.height + tile_size - 1) / tile_size;
    let total = (cols * rows) as usize;

    // Step 1: Hash each tile using FNV-1a
    let mut current_hashes = vec![0u64; total];
    for r in 0..rows {
        for c in 0..cols {
            let idx = (r * cols + c) as usize;
            current_hashes[idx] = hash_tile(frame, c, r, tile_size);
        }
    }

    // Step 2: Delta detect against previous frame
    let changed_indices: Vec<u32> = match prev_hashes {
        None => (0..total as u32).collect(), // first frame: all changed
        Some(prev) => (0..total)
            .filter(|&i| i >= prev.len() || current_hashes[i] != prev[i])
            .map(|i| i as u32)
            .collect(),
    };

    // Step 3: Extract features for changed tiles only
    let gray = to_grayscale(frame);
    let tiles: Vec<TileDescriptor> = changed_indices
        .iter()
        .map(|&idx| {
            let col = (idx % cols) as usize;
            let row = (idx / cols) as usize;
            extract_tile_features(frame, &gray, col, row, tile_size as usize)
        })
        .collect();

    // Step 4: Update state for next call
    *prev_hashes = Some(current_hashes);

    CompressedFrame {
        width: frame.width,
        height: frame.height,
        tile_size,
        total_tiles: total as u32,
        changed_tiles: tiles.len() as u32,
        tiles,
    }
}

/// Convert a BGRA frame to single-channel grayscale.
///
/// Uses the standard luminance formula: `0.299*R + 0.587*G + 0.114*B`.
/// BGRA layout: data[px+0]=B, data[px+1]=G, data[px+2]=R, data[px+3]=A.
pub fn to_grayscale(frame: &Frame) -> Vec<u8> {
    let pixel_count = (frame.width as usize) * (frame.height as usize);
    let mut gray = Vec::with_capacity(pixel_count);
    for i in 0..pixel_count {
        let px = i * 4;
        let b = frame.data[px] as f32;
        let g = frame.data[px + 1] as f32;
        let r = frame.data[px + 2] as f32;
        // Standard luminance: 0.299*R + 0.587*G + 0.114*B
        let lum = 0.299 * r + 0.587 * g + 0.114 * b;
        gray.push(lum.round() as u8);
    }
    gray
}

/// Extract per-tile features: mean color (RGBA), edge density, likely_text.
///
/// - **mean_color**: Average RGBA values across all pixels in the tile.
///   Converts from BGRA source order to RGBA output order.
/// - **edge_density**: Sobel approximation on the grayscale tile, normalized to [0.0, 1.0].
/// - **likely_text**: `edge_density > 0.05 && edge_density < 0.4`.
pub fn extract_tile_features(
    frame: &Frame,
    gray: &[u8],
    col: usize,
    row: usize,
    tile_size: usize,
) -> TileDescriptor {
    let x0 = col * tile_size;
    let y0 = row * tile_size;
    let w = frame.width as usize;
    let h = frame.height as usize;

    // Clamp tile dimensions to frame bounds (edge tiles may be smaller)
    let tw = tile_size.min(w.saturating_sub(x0));
    let th = tile_size.min(h.saturating_sub(y0));
    let pixel_count = tw * th;

    if pixel_count == 0 {
        return TileDescriptor {
            col: col as u16,
            row: row as u16,
            mean_color: [0, 0, 0, 0],
            edge_density: 0.0,
            likely_text: false,
        };
    }

    // --- Mean color (BGRA source -> RGBA output) ---
    let mut sum_r: u64 = 0;
    let mut sum_g: u64 = 0;
    let mut sum_b: u64 = 0;
    let mut sum_a: u64 = 0;

    for dy in 0..th {
        let y = y0 + dy;
        for dx in 0..tw {
            let x = x0 + dx;
            let px = (y * w + x) * 4;
            sum_b += frame.data[px] as u64;
            sum_g += frame.data[px + 1] as u64;
            sum_r += frame.data[px + 2] as u64;
            sum_a += frame.data[px + 3] as u64;
        }
    }

    let n = pixel_count as u64;
    let mean_color = [
        (sum_r / n) as u8, // R
        (sum_g / n) as u8, // G
        (sum_b / n) as u8, // B
        (sum_a / n) as u8, // A
    ];

    // --- Edge density via Sobel approximation ---
    let edge_density = compute_edge_density(gray, x0, y0, tw, th, w, h);

    let likely_text = edge_density > 0.05 && edge_density < 0.4;

    TileDescriptor {
        col: col as u16,
        row: row as u16,
        mean_color,
        edge_density,
        likely_text,
    }
}

/// Compute edge density for a tile region using Sobel approximation.
///
/// For each pixel with a full 3x3 neighborhood, computes the Sobel
/// gradient magnitude. The edge density is the mean normalized gradient
/// across all valid pixels, clamped to [0.0, 1.0].
pub fn compute_edge_density(
    gray: &[u8],
    x0: usize,
    y0: usize,
    tw: usize,
    th: usize,
    frame_w: usize,
    frame_h: usize,
) -> f32 {
    if tw < 2 || th < 2 {
        return 0.0;
    }

    // Sobel kernels:
    // Gx = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]
    // Gy = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]]

    let mut gradient_sum: f64 = 0.0;
    let mut count: u32 = 0;

    // Iterate over pixels that have a full 3x3 neighborhood within the frame
    for dy in 0..th {
        let y = y0 + dy;
        if y == 0 || y >= frame_h - 1 {
            continue;
        }
        for dx in 0..tw {
            let x = x0 + dx;
            if x == 0 || x >= frame_w - 1 {
                continue;
            }

            // 3x3 neighborhood from grayscale buffer
            let tl = gray[(y - 1) * frame_w + (x - 1)] as f64;
            let tc = gray[(y - 1) * frame_w + x] as f64;
            let tr = gray[(y - 1) * frame_w + (x + 1)] as f64;
            let ml = gray[y * frame_w + (x - 1)] as f64;
            let mr = gray[y * frame_w + (x + 1)] as f64;
            let bl = gray[(y + 1) * frame_w + (x - 1)] as f64;
            let bc = gray[(y + 1) * frame_w + x] as f64;
            let br = gray[(y + 1) * frame_w + (x + 1)] as f64;

            let gx = -tl + tr - 2.0 * ml + 2.0 * mr - bl + br;
            let gy = -tl - 2.0 * tc - tr + bl + 2.0 * bc + br;

            let magnitude = (gx * gx + gy * gy).sqrt();
            // Normalize: max possible Sobel magnitude for 8-bit input is
            // sqrt((4*255)^2 + (4*255)^2) = 255*4*sqrt(2) ~ 1442.5
            gradient_sum += magnitude / 1442.5;
            count += 1;
        }
    }

    if count == 0 {
        return 0.0;
    }

    let density = (gradient_sum / count as f64) as f32;
    // Clamp to [0.0, 1.0] for safety
    density.clamp(0.0, 1.0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::inlined_types::Frame;
    use proptest::prelude::*;
    use proptest::collection::vec;

    #[test]
    fn test_hash_tile_deterministic() {
        let frame = Frame::new(4, 4, vec![42u8; 4 * 4 * 4]);
        let h1 = hash_tile(&frame, 0, 0, 4);
        let h2 = hash_tile(&frame, 0, 0, 4);
        assert_eq!(h1, h2, "FNV-1a hash must be deterministic");
    }

    #[test]
    fn test_hash_tile_different_data() {
        let frame_a = Frame::new(4, 4, vec![0u8; 4 * 4 * 4]);
        let frame_b = Frame::new(4, 4, vec![255u8; 4 * 4 * 4]);
        let ha = hash_tile(&frame_a, 0, 0, 4);
        let hb = hash_tile(&frame_b, 0, 0, 4);
        assert_ne!(ha, hb, "Different pixel data should produce different hashes");
    }

    #[test]
    fn test_compress_first_frame_all_changed() {
        let frame = Frame::new(32, 32, vec![128u8; 32 * 32 * 4]);
        let mut prev = None;
        let cf = cpu_compress_frame(&frame, &mut prev, 16);
        // 32/16 = 2 cols, 2 rows = 4 tiles
        assert_eq!(cf.total_tiles, 4);
        assert_eq!(cf.changed_tiles, 4);
        assert_eq!(cf.tiles.len(), 4);
    }

    #[test]
    fn test_compress_static_screen_zero_changes() {
        let frame = Frame::new(32, 32, vec![128u8; 32 * 32 * 4]);
        let mut prev = None;
        let _ = cpu_compress_frame(&frame, &mut prev, 16);
        let cf2 = cpu_compress_frame(&frame, &mut prev, 16);
        assert_eq!(cf2.changed_tiles, 0);
        assert!(cf2.tiles.is_empty());
    }

    #[test]
    fn test_compress_edge_tiles() {
        // 17x17 with tile_size=16 -> 2x2 = 4 tiles (edge tiles are 1px wide/tall)
        let frame = Frame::new(17, 17, vec![100u8; 17 * 17 * 4]);
        let mut prev = None;
        let cf = cpu_compress_frame(&frame, &mut prev, 16);
        assert_eq!(cf.total_tiles, 4);
        assert_eq!(cf.changed_tiles, 4);
    }

    #[test]
    fn test_tile_descriptor_mean_color_bgra_to_rgba() {
        // All pixels: B=10, G=20, R=30, A=255
        let mut data = Vec::new();
        for _ in 0..(16 * 16) {
            data.extend_from_slice(&[10, 20, 30, 255]); // BGRA
        }
        let frame = Frame::new(16, 16, data);
        let mut prev = None;
        let cf = cpu_compress_frame(&frame, &mut prev, 16);
        assert_eq!(cf.tiles.len(), 1);
        let tile = &cf.tiles[0];
        // Output should be RGBA: R=30, G=20, B=10, A=255
        assert_eq!(tile.mean_color, [30, 20, 10, 255]);
    }

    #[test]
    fn test_edge_density_flat_image() {
        // Uniform image -> edge density should be 0.0
        let frame = Frame::new(16, 16, vec![128u8; 16 * 16 * 4]);
        let mut prev = None;
        let cf = cpu_compress_frame(&frame, &mut prev, 16);
        assert_eq!(cf.tiles.len(), 1);
        assert_eq!(cf.tiles[0].edge_density, 0.0);
        assert!(!cf.tiles[0].likely_text);
    }

    #[test]
    fn test_edge_density_bounds() {
        // Patterned data -- edge density must be in [0.0, 1.0]
        let data: Vec<u8> = (0..16 * 16 * 4).map(|i| (i % 256) as u8).collect();
        let frame = Frame::new(16, 16, data);
        let mut prev = None;
        let cf = cpu_compress_frame(&frame, &mut prev, 16);
        for tile in &cf.tiles {
            assert!(
                tile.edge_density >= 0.0 && tile.edge_density <= 1.0,
                "edge_density {} out of bounds",
                tile.edge_density
            );
        }
    }

    #[test]
    fn test_likely_text_derivation() {
        // Verify likely_text matches the formula exactly
        let data: Vec<u8> = (0..16 * 16 * 4).map(|i| (i % 256) as u8).collect();
        let frame = Frame::new(16, 16, data);
        let mut prev = None;
        let cf = cpu_compress_frame(&frame, &mut prev, 16);
        for tile in &cf.tiles {
            let expected = tile.edge_density > 0.05 && tile.edge_density < 0.4;
            assert_eq!(
                tile.likely_text, expected,
                "likely_text mismatch for edge_density={}",
                tile.edge_density
            );
        }
    }

    #[test]
    fn test_to_grayscale() {
        // Single pixel: B=0, G=0, R=255, A=255 -> gray ~ 0.299*255 = 76
        let frame = Frame::new(1, 1, vec![0, 0, 255, 255]);
        let gray = to_grayscale(&frame);
        assert_eq!(gray.len(), 1);
        assert_eq!(gray[0], 76); // 0.299 * 255 ~ 76.245 -> 76
    }

    #[test]
    fn test_total_tiles_formula() {
        // Verify total_tiles == ceil(w/ts) * ceil(h/ts)
        for (w, h, ts) in [(100, 100, 16), (1920, 1080, 16), (1, 1, 16), (33, 17, 8)] {
            let frame = Frame::new(w, h, vec![0u8; (w as usize) * (h as usize) * 4]);
            let mut prev = None;
            let cf = cpu_compress_frame(&frame, &mut prev, ts);
            let expected_cols = (w + ts - 1) / ts;
            let expected_rows = (h + ts - 1) / ts;
            assert_eq!(
                cf.total_tiles,
                expected_cols * expected_rows,
                "total_tiles mismatch for {}x{} ts={}",
                w,
                h,
                ts
            );
        }
    }

    proptest! {
        // Feature: forgewright-oss, Property 12: Tile grid dimensions and hash count
        // **Validates: Requirements 8.1, 8.5, 8.6**
        #[test]
        fn prop_tile_grid_dimensions_and_hash_count(
            w in 1u32..=256,
            h in 1u32..=256,
            tile_size in 1u32..=64,
        ) {
            let data = vec![0u8; (w as usize) * (h as usize) * 4];
            let frame = Frame::new(w, h, data);
            let mut prev = None;
            let cf = cpu_compress_frame(&frame, &mut prev, tile_size);

            let expected_cols = (w + tile_size - 1) / tile_size;
            let expected_rows = (h + tile_size - 1) / tile_size;
            let expected_total = expected_cols * expected_rows;

            prop_assert_eq!(cf.total_tiles, expected_total,
                "total_tiles mismatch for {}x{} ts={}", w, h, tile_size);
            prop_assert_eq!(cf.changed_tiles, expected_total,
                "first frame should have all tiles changed for {}x{} ts={}", w, h, tile_size);
            prop_assert_eq!(cf.tiles.len(), expected_total as usize,
                "tiles.len() mismatch for {}x{} ts={}", w, h, tile_size);
        }

        // Feature: forgewright-oss, Property 16: Tile feature invariants
        // **Validates: Requirements 8.8**
        #[test]
        fn prop_tile_feature_invariants(
            w in 1u32..=64,
            h in 1u32..=64,
            tile_size in 1u32..=32,
            data in vec(any::<u8>(), 1..=(64 * 64 * 4) as usize),
        ) {
            // Ensure data length matches frame dimensions
            let needed = (w as usize) * (h as usize) * 4;
            prop_assume!(data.len() >= needed);
            let pixel_data = data[..needed].to_vec();
            let frame = Frame::new(w, h, pixel_data);
            let mut prev = None;
            let cf = cpu_compress_frame(&frame, &mut prev, tile_size);

            for tile in &cf.tiles {
                prop_assert!(
                    tile.edge_density >= 0.0 && tile.edge_density <= 1.0,
                    "edge_density {} out of [0.0, 1.0] bounds", tile.edge_density
                );
                prop_assert_eq!(
                    tile.likely_text,
                    tile.edge_density > 0.05 && tile.edge_density < 0.4,
                    "likely_text mismatch for edge_density={}", tile.edge_density
                );
                // mean_color channels are u8, so trivially in [0, 255],
                // but we validate the type is correct
                let [_r, _g, _b, _a] = tile.mean_color;
            }
        }
    }
}