crabcamera 0.9.2

Advanced cross-platform camera integration for Tauri applications
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
467
468
469
470
471
use crate::constants::{
    EXPOSURE_BRIGHTNESS_DARK, EXPOSURE_BRIGHTNESS_GOOD, EXPOSURE_BRIGHTNESS_HIGH,
    EXPOSURE_BRIGHTNESS_LOW, EXPOSURE_PIXEL_BRIGHT, EXPOSURE_PIXEL_DARK, QUALITY_SCORE_BLURRY,
    QUALITY_SCORE_GOOD, QUALITY_SCORE_SHARP,
};
use crate::types::CameraFrame;
use serde::{Deserialize, Serialize};

/// Exposure analysis levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ExposureLevel {
    /// Image is too dark. Details lost in shadows.
    Underexposed,
    /// Slightly dark but potentially usable or fixable.
    SlightlyDark,
    /// Optimal exposure. Good balance of light and dark.
    WellExposed,
    /// Slightly bright but acceptable.
    SlightlyBright,
    /// Image is too bright. Details lost in highlights.
    Overexposed,
}

impl ExposureLevel {
    /// Convert brightness to exposure level
    #[must_use]
    pub fn from_brightness(brightness: f32) -> Self {
        if brightness < EXPOSURE_BRIGHTNESS_LOW {
            Self::Underexposed
        } else if brightness < EXPOSURE_BRIGHTNESS_DARK {
            Self::SlightlyDark
        } else if brightness < EXPOSURE_BRIGHTNESS_GOOD {
            Self::WellExposed
        } else if brightness < EXPOSURE_BRIGHTNESS_HIGH {
            Self::SlightlyBright
        } else {
            Self::Overexposed
        }
    }

    /// Get quality score (0.0 to 1.0)
    #[must_use]
    pub fn quality_score(self) -> f32 {
        match self {
            Self::WellExposed => QUALITY_SCORE_SHARP, // 1.0
            Self::SlightlyDark | Self::SlightlyBright => QUALITY_SCORE_GOOD, // 0.8
            Self::Underexposed | Self::Overexposed => QUALITY_SCORE_BLURRY, // 0.3
        }
    }
}

/// Exposure analysis metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExposureMetrics {
    /// Average brightness (0.0 to 1.0)
    pub mean_brightness: f32,
    /// Standard deviation of brightness.
    /// Indicates contrast and variety of logical brightness in the image.
    pub brightness_std: f32,
    /// 256-bin brightness histogram.
    /// Distribution of pixel intensities.
    pub histogram: Vec<u32>,
    /// Ratio of very dark pixels (pixels below dark threshold).
    pub dark_pixel_ratio: f32,
    /// Ratio of very bright pixels (pixels above bright threshold)
    pub bright_pixel_ratio: f32,
    /// Difference between min and max brightness.
    pub dynamic_range: f32,
    /// Overall exposure assessment level.
    pub exposure_level: ExposureLevel,
    /// Calculated quality score (0.0 to 1.0)
    pub quality_score: f32,
}

/// Exposure analyzer for image quality assessment
pub struct ExposureAnalyzer {
    /// Pixels below this are considered dark
    dark_threshold: u8,
    /// Pixels above this are considered bright
    bright_threshold: u8,
}

impl Default for ExposureAnalyzer {
    fn default() -> Self {
        Self {
            dark_threshold: EXPOSURE_PIXEL_DARK, // Pixels below this are considered dark
            bright_threshold: EXPOSURE_PIXEL_BRIGHT, // Pixels above this are considered bright
        }
    }
}

impl ExposureAnalyzer {
    /// Create new exposure analyzer with custom thresholds
    pub fn new(dark_threshold: u8, bright_threshold: u8) -> Self {
        Self {
            dark_threshold,
            bright_threshold,
        }
    }

    /// Analyze frame exposure
    pub fn analyze_frame(&self, frame: &CameraFrame) -> ExposureMetrics {
        // Convert to grayscale for luminance analysis
        let grayscale = Self::rgb_to_luminance(&frame.data, frame.width, frame.height);

        // Calculate histogram
        let histogram = Self::calculate_histogram(&grayscale);

        // Calculate brightness statistics
        let mean_brightness = Self::calculate_mean_brightness(&grayscale);
        let brightness_std = Self::calculate_brightness_std(&grayscale, mean_brightness);

        // Calculate pixel ratios
        // Uses self thresholds
        let dark_pixel_ratio = self.calculate_dark_pixel_ratio(&grayscale);
        let bright_pixel_ratio = self.calculate_bright_pixel_ratio(&grayscale);

        // Calculate dynamic range
        let dynamic_range = Self::calculate_dynamic_range(&histogram);

        // Determine exposure level
        let exposure_level = ExposureLevel::from_brightness(mean_brightness);
        let quality_score =
            Self::calculate_quality_score(exposure_level, brightness_std, dynamic_range);

        ExposureMetrics {
            mean_brightness,
            brightness_std,
            histogram,
            dark_pixel_ratio,
            bright_pixel_ratio,
            dynamic_range,
            exposure_level,
            quality_score,
        }
    }

    /// Convert RGB to luminance using standard weights
    fn rgb_to_luminance(rgb_data: &[u8], width: u32, height: u32) -> Vec<u8> {
        let mut luminance = Vec::with_capacity((width * height) as usize);

        for i in (0..rgb_data.len()).step_by(3) {
            if i + 2 >= rgb_data.len() {
                break;
            }
            let r = f32::from(rgb_data[i]);
            let g = f32::from(rgb_data[i + 1]);
            let b = f32::from(rgb_data[i + 2]);

            // ITU-R BT.709 luminance weights
            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
            let y = (0.2126 * r + 0.7152 * g + 0.0722 * b)
                .round()
                .clamp(0.0, 255.0) as u8;
            luminance.push(y);
        }

        luminance
    }

    /// Calculate 256-bin histogram
    fn calculate_histogram(luminance: &[u8]) -> Vec<u32> {
        let mut histogram = vec![0u32; 256];
        for &pixel in luminance {
            histogram[pixel as usize] += 1;
        }
        histogram
    }

    /// Calculate mean brightness (0.0 to 1.0)
    fn calculate_mean_brightness(luminance: &[u8]) -> f32 {
        if luminance.is_empty() {
            return 0.0;
        }

        let sum: u64 = luminance.iter().map(|&x| u64::from(x)).sum();
        #[allow(clippy::cast_precision_loss)]
        let sum_f = sum as f32;
        #[allow(clippy::cast_precision_loss)]
        let len_f = luminance.len() as f32;
        sum_f / (len_f * 255.0)
    }

    /// Calculate brightness standard deviation
    fn calculate_brightness_std(luminance: &[u8], mean: f32) -> f32 {
        if luminance.is_empty() {
            return 0.0;
        }

        let mean_255 = mean * 255.0; // Convert back to 0-255 scale
                                     // Variance calculation
        #[allow(clippy::cast_precision_loss)]
        let len_f = luminance.len() as f32;
        let variance: f32 = luminance
            .iter()
            .map(|&x| (f32::from(x) - mean_255).powi(2))
            .sum::<f32>()
            / len_f;

        variance.sqrt() / 255.0 // Normalize to 0-1 scale
    }

    /// Calculate ratio of dark pixels based on threshold
    fn calculate_dark_pixel_ratio(&self, luminance: &[u8]) -> f32 {
        if luminance.is_empty() {
            return 0.0;
        }

        let dark_count = luminance
            .iter()
            .filter(|&&x| x < self.dark_threshold)
            .count();

        #[allow(clippy::cast_precision_loss)]
        let dark_f = dark_count as f32;
        #[allow(clippy::cast_precision_loss)]
        let len_f = luminance.len() as f32;
        dark_f / len_f
    }

    /// Calculate ratio of bright pixels based on threshold
    fn calculate_bright_pixel_ratio(&self, luminance: &[u8]) -> f32 {
        if luminance.is_empty() {
            return 0.0;
        }

        let bright_count = luminance
            .iter()
            .filter(|&&x| x > self.bright_threshold)
            .count();

        #[allow(clippy::cast_precision_loss)]
        let bright_f = bright_count as f32;
        #[allow(clippy::cast_precision_loss)]
        let len_f = luminance.len() as f32;
        bright_f / len_f
    }

    /// Calculate dynamic range
    fn calculate_dynamic_range(histogram: &[u32]) -> f32 {
        let mut min_value = 255;
        let mut max_value = 0;

        // Find minimum non-zero bin
        for (i, &count) in histogram.iter().enumerate() {
            if count > 0 {
                min_value = i;
                break;
            }
        }

        // Find maximum non-zero bin
        for (i, &count) in histogram.iter().enumerate().rev() {
            if count > 0 {
                max_value = i;
                break;
            }
        }

        if max_value > min_value {
            #[allow(clippy::cast_precision_loss)]
            let range = (max_value - min_value) as f32;
            range / 255.0
        } else {
            0.0
        }
    }

    /// Calculate overall quality score
    #[allow(clippy::similar_names)]
    fn calculate_quality_score(
        exposure_level: ExposureLevel,
        brightness_std: f32,
        dynamic_range: f32,
    ) -> f32 {
        let exposure_score = exposure_level.quality_score();

        // Bonus for good contrast (standard deviation)
        let contrast_score = if brightness_std > 0.15 && brightness_std < 0.35 {
            1.0
        } else if brightness_std > 0.1 && brightness_std < 0.4 {
            0.8
        } else {
            0.5
        };

        // Bonus for good dynamic range
        let range_score = if dynamic_range > 0.7 {
            1.0
        } else if dynamic_range > 0.5 {
            0.8
        } else if dynamic_range > 0.3 {
            0.6
        } else {
            0.4
        };

        // Weighted combination
        (exposure_score * 0.6 + contrast_score * 0.25 + range_score * 0.15).clamp(0.0, 1.0)
    }

    /// Check if exposure is acceptable
    pub fn is_acceptable_exposure(&self, metrics: &ExposureMetrics) -> bool {
        matches!(
            metrics.exposure_level,
            ExposureLevel::WellExposed
                | ExposureLevel::SlightlyDark
                | ExposureLevel::SlightlyBright
        )
    }

    /// Get exposure correction recommendation
    pub fn get_exposure_correction(&self, metrics: &ExposureMetrics) -> ExposureCorrection {
        match metrics.exposure_level {
            ExposureLevel::Underexposed => ExposureCorrection::IncreaseExposure(1.5),
            ExposureLevel::SlightlyDark => ExposureCorrection::IncreaseExposure(1.2),
            ExposureLevel::WellExposed => ExposureCorrection::NoChange,
            ExposureLevel::SlightlyBright => ExposureCorrection::DecreaseExposure(0.8),
            ExposureLevel::Overexposed => ExposureCorrection::DecreaseExposure(0.6),
        }
    }
}

/// Exposure correction recommendations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExposureCorrection {
    /// No exposure change needed.
    NoChange,
    /// Increase exposure by multiplier.
    IncreaseExposure(f32),
    /// Decrease exposure by multiplier.
    DecreaseExposure(f32),
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_frame_with_brightness(width: u32, height: u32, brightness: u8) -> CameraFrame {
        let size = (width * height * 3) as usize;
        let data = vec![brightness; size];
        CameraFrame::new(data, width, height, "test".to_string())
    }

    #[test]
    fn test_exposure_level_from_brightness() {
        assert_eq!(
            ExposureLevel::from_brightness(0.1),
            ExposureLevel::Underexposed
        );
        assert_eq!(
            ExposureLevel::from_brightness(0.3),
            ExposureLevel::SlightlyDark
        );
        assert_eq!(
            ExposureLevel::from_brightness(0.5),
            ExposureLevel::WellExposed
        );
        assert_eq!(
            ExposureLevel::from_brightness(0.7),
            ExposureLevel::SlightlyBright
        );
        assert_eq!(
            ExposureLevel::from_brightness(0.9),
            ExposureLevel::Overexposed
        );
    }

    #[test]
    fn test_exposure_level_quality_score() {
        let epsilon = 1e-10;
        assert!((ExposureLevel::WellExposed.quality_score() - 1.0).abs() < epsilon);
        assert!((ExposureLevel::SlightlyDark.quality_score() - 0.8).abs() < epsilon);
        assert!((ExposureLevel::SlightlyBright.quality_score() - 0.8).abs() < epsilon);
        assert!((ExposureLevel::Underexposed.quality_score() - 0.3).abs() < epsilon);
        assert!((ExposureLevel::Overexposed.quality_score() - 0.3).abs() < epsilon);
    }

    #[test]
    fn test_exposure_analyzer_creation() {
        let analyzer = ExposureAnalyzer::default();
        assert_eq!(analyzer.dark_threshold, 30);
        assert_eq!(analyzer.bright_threshold, 225);

        let custom_analyzer = ExposureAnalyzer::new(20, 240);
        assert_eq!(custom_analyzer.dark_threshold, 20);
        assert_eq!(custom_analyzer.bright_threshold, 240);
    }

    #[test]
    fn test_rgb_to_luminance() {
        let _analyzer = ExposureAnalyzer::default();
        let rgb_data = vec![255, 255, 255, 0, 0, 0]; // White, Black
        let luminance = ExposureAnalyzer::rgb_to_luminance(&rgb_data, 2, 1);

        assert_eq!(luminance.len(), 2);
        assert!(luminance[0] > 250); // White should be bright
        assert!(luminance[1] < 5); // Black should be dark
    }

    #[test]
    fn test_histogram_calculation() {
        let _analyzer = ExposureAnalyzer::default();
        let luminance = vec![0, 128, 255, 128]; // Various brightness levels
        let histogram = ExposureAnalyzer::calculate_histogram(&luminance);

        assert_eq!(histogram.len(), 256);
        assert_eq!(histogram[0], 1); // One black pixel
        assert_eq!(histogram[128], 2); // Two mid-gray pixels
        assert_eq!(histogram[255], 1); // One white pixel
    }

    #[test]
    fn test_dark_frame_analysis() {
        let analyzer = ExposureAnalyzer::default();
        let dark_frame = create_test_frame_with_brightness(50, 50, 20);

        let metrics = analyzer.analyze_frame(&dark_frame);

        assert!(metrics.mean_brightness < 0.2);
        assert_eq!(metrics.exposure_level, ExposureLevel::Underexposed);
        assert!(metrics.dark_pixel_ratio > 0.5);
    }

    #[test]
    fn test_bright_frame_analysis() {
        let analyzer = ExposureAnalyzer::default();
        let bright_frame = create_test_frame_with_brightness(50, 50, 240);

        let metrics = analyzer.analyze_frame(&bright_frame);

        assert!(metrics.mean_brightness > 0.8);
        assert_eq!(metrics.exposure_level, ExposureLevel::Overexposed);
        assert!(metrics.bright_pixel_ratio > 0.5);
    }

    #[test]
    fn test_well_exposed_frame() {
        let analyzer = ExposureAnalyzer::default();
        let well_exposed_frame = create_test_frame_with_brightness(50, 50, 128);

        let metrics = analyzer.analyze_frame(&well_exposed_frame);

        assert!(metrics.mean_brightness > 0.4 && metrics.mean_brightness < 0.6);
        assert_eq!(metrics.exposure_level, ExposureLevel::WellExposed);
        assert!(analyzer.is_acceptable_exposure(&metrics));
    }

    #[test]
    fn test_exposure_correction() {
        let analyzer = ExposureAnalyzer::default();

        let dark_metrics = ExposureMetrics {
            mean_brightness: 0.1,
            brightness_std: 0.05,
            histogram: vec![0; 256],
            dark_pixel_ratio: 0.8,
            bright_pixel_ratio: 0.0,
            dynamic_range: 0.2,
            exposure_level: ExposureLevel::Underexposed,
            quality_score: 0.3,
        };

        match analyzer.get_exposure_correction(&dark_metrics) {
            ExposureCorrection::IncreaseExposure(factor) => {
                assert!(factor > 1.0);
            }
            _ => panic!("Expected IncreaseExposure for dark image"),
        }
    }
}