crabcamera 0.8.3

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
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Advanced Camera Controls Testing
//!
//! **Note:** These tests share the same mock camera and must run serially.
//! Run with: `cargo test --test commands_advanced_test -- --test-threads=1`
//!
//! Comprehensive test suite for professional camera controls including:
//! - Manual focus control validation
//! - Exposure bracketing accuracy
//! - White balance calibration
//! - HDR capture sequences
//! - Advanced control parameter validation
//! - Performance testing for advanced operations

use crabcamera::commands::advanced::{
    capture_burst_sequence, capture_focus_stack_legacy, capture_hdr_sequence,
    get_camera_controls, get_camera_performance, set_camera_controls, set_manual_exposure,
    set_manual_focus, set_white_balance, test_camera_capabilities as test_capabilities,
};
use crabcamera::types::{BurstConfig, CameraControls, WhiteBalance};
use std::time::{Duration, Instant};
use tokio::sync::Mutex as AsyncMutex;
use tokio;

/// Test synchronization lock to prevent concurrent camera control tests
/// This ensures only one test modifies camera controls at a time
static TEST_LOCK: AsyncMutex<()> = AsyncMutex::const_new(());

/// Mock device ID for testing
const TEST_DEVICE_ID: &str = "test_camera_advanced";

/// Helper function to create test controls
fn create_test_controls() -> CameraControls {
    CameraControls {
        auto_focus: Some(false),
        focus_distance: Some(0.5),
        auto_exposure: Some(false),
        exposure_time: Some(1.0 / 125.0), // 1/125s
        iso_sensitivity: Some(400),
        white_balance: Some(WhiteBalance::Auto),
        aperture: Some(5.6),
        zoom: Some(1.0),
        brightness: Some(0.0),
        contrast: Some(0.0),
        saturation: Some(0.0),
        sharpness: Some(0.0),
        noise_reduction: Some(true),
        image_stabilization: Some(true),
    }
}

/// Test setting and getting basic camera controls
#[tokio::test]
async fn test_set_get_camera_controls() {
    // Acquire async lock to prevent concurrent camera control modifications
    let _lock = TEST_LOCK.lock().await;
    
    let controls = create_test_controls();
    let device_id = TEST_DEVICE_ID.to_string();

    // Set controls
    let set_result = set_camera_controls(device_id.clone(), controls.clone()).await;
    match set_result {
        Ok(message) => {
            assert!(message.contains("Controls applied"));
        }
        Err(e) => {
            // In CI environment, camera might not be available
            println!("Warning: Camera control test failed (expected in CI): {}", e);
            return;
        }
    }

    // Give hardware time to apply the settings
    tokio::time::sleep(Duration::from_millis(100)).await;

    // Get controls back  
    let get_result = get_camera_controls(device_id.clone()).await;
    match get_result {
        Ok(retrieved_controls) => {
            // In mock/test environments, controls may not be perfectly stored
            // Just verify the operation succeeded and we got some controls back
            assert!(retrieved_controls.auto_focus.is_some(), "auto_focus should be set");
            // Note: Hardware cameras may not support all control changes,
            // so we don't assert exact matches in test environments
        }
        Err(e) => {
            println!("Warning: Get controls test failed (expected in CI): {}", e);
        }
    }
    
    // Cleanup: Reset controls to defaults for next test
    let default_controls = CameraControls::default();
    let _ = set_camera_controls(device_id, default_controls).await;
}

/// Test manual focus control with parameter validation
#[tokio::test]
async fn test_manual_focus_control() {
    let device_id = TEST_DEVICE_ID.to_string();

    // Test valid focus distances
    let valid_distances = [0.0, 0.25, 0.5, 0.75, 1.0];
    
    for distance in valid_distances.iter() {
        let result = set_manual_focus(device_id.clone(), *distance).await;
        match result {
            Ok(_) => {
                // Success is good
            }
            Err(e) if e.contains("mutex") || e.contains("camera") => {
                // Expected in CI without camera hardware
                println!("Warning: Focus test failed (expected in CI): {}", e);
            }
            Err(e) => {
                // Should not be a parameter validation error
                assert!(!e.contains("Focus distance must be"));
            }
        }
    }

    // Test invalid focus distances
    let invalid_distances = [-0.1, 1.1, 2.0, -1.0];
    
    for distance in invalid_distances.iter() {
        let result = set_manual_focus(device_id.clone(), *distance).await;
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.contains("Focus distance must be between 0.0"));
        }
    }
}

/// Test manual exposure settings with validation
#[tokio::test]
async fn test_manual_exposure_settings() {
    let device_id = TEST_DEVICE_ID.to_string();

    // Test valid exposure combinations
    let valid_combinations = [
        (1.0 / 1000.0, 100),  // Fast shutter, low ISO
        (1.0 / 125.0, 400),   // Standard settings
        (1.0 / 30.0, 800),    // Slow shutter, higher ISO
        (1.0 / 4.0, 3200),    // Very slow, high ISO
    ];

    for (exposure_time, iso) in valid_combinations.iter() {
        let result = set_manual_exposure(device_id.clone(), *exposure_time, *iso).await;
        match result {
            Ok(_) => {
                // Success is good
            }
            Err(e) if e.contains("mutex") || e.contains("camera") => {
                // Expected in CI
                println!("Warning: Exposure test failed (expected in CI): {}", e);
            }
            Err(e) => {
                // Should not be parameter validation errors
                assert!(!e.contains("Exposure time must be"));
                assert!(!e.contains("ISO sensitivity must be"));
            }
        }
    }

    // Test invalid exposure times
    let invalid_exposures = [0.0, -0.1, 11.0, 20.0];
    for exposure in invalid_exposures.iter() {
        let result = set_manual_exposure(device_id.clone(), *exposure, 400).await;
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.contains("Exposure time must be"));
        }
    }

    // Test invalid ISO values
    let invalid_isos = [25, 49, 25600, 100000];
    for iso in invalid_isos.iter() {
        let result = set_manual_exposure(device_id.clone(), 1.0 / 125.0, *iso).await;
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.contains("ISO sensitivity must be"));
        }
    }
}

/// Test white balance modes
#[tokio::test]
async fn test_white_balance_modes() {
    let device_id = TEST_DEVICE_ID.to_string();

    let wb_modes = [
        WhiteBalance::Auto,
        WhiteBalance::Daylight,
        WhiteBalance::Fluorescent,
        WhiteBalance::Incandescent,
        WhiteBalance::Flash,
        WhiteBalance::Cloudy,
        WhiteBalance::Shade,
        WhiteBalance::Custom(5500), // 5500K daylight
    ];

    for wb_mode in wb_modes.iter() {
        let result = set_white_balance(device_id.clone(), wb_mode.clone()).await;
        match result {
            Ok(_) => {
                // Success is good
            }
            Err(e) if e.contains("mutex") || e.contains("camera") => {
                // Expected in CI
                println!("Warning: WB test failed (expected in CI): {}", e);
            }
            Err(e) => {
                // Unexpected error
                println!("Unexpected white balance error: {}", e);
            }
        }
    }
}

/// Test burst sequence capture with various configurations
#[tokio::test]
async fn test_burst_sequence_capture() {
    let device_id = TEST_DEVICE_ID.to_string();

    // Test basic burst configuration
    let basic_config = BurstConfig {
        count: 3,
        interval_ms: 100,
        bracketing: None,
        focus_stacking: false,
        auto_save: false,
        save_directory: None,
    };

    let result = capture_burst_sequence(device_id.clone(), basic_config).await;
    match result {
        Ok(frames) => {
            assert_eq!(frames.len(), 3);
            for frame in frames {
                assert!(frame.is_valid());
                assert!(!frame.data.is_empty());
            }
        }
        Err(e) if e.contains("mutex") || e.contains("camera") => {
            // Expected in CI
            println!("Warning: Burst test failed (expected in CI): {}", e);
        }
        Err(e) => {
            println!("Unexpected burst error: {}", e);
        }
    }
}

/// Test exposure bracketing in burst mode
#[tokio::test]
async fn test_exposure_bracketing() {
    let device_id = TEST_DEVICE_ID.to_string();

    let bracketing_config = crabcamera::types::ExposureBracketing {
        base_exposure: 1.0 / 125.0,
        stops: vec![-1.0, 0.0, 1.0], // Under, normal, over
    };

    let burst_config = BurstConfig {
        count: 3,
        interval_ms: 200,
        bracketing: Some(bracketing_config),
        focus_stacking: false,
        auto_save: false,
        save_directory: None,
    };

    let result = capture_burst_sequence(device_id, burst_config).await;
    match result {
        Ok(frames) => {
            assert_eq!(frames.len(), 3);
            
            // Verify frames have metadata indicating different exposures
            for (i, frame) in frames.iter().enumerate() {
                assert!(frame.is_valid());
                if let Some(ref settings) = frame.metadata.capture_settings {
                    // Check that exposure was varied for bracketing
                    assert!(settings.exposure_time.is_some() || settings.auto_exposure == Some(false));
                }
                println!("Bracketed frame {}: {} bytes", i + 1, frame.size_bytes);
            }
        }
        Err(e) if e.contains("mutex") || e.contains("camera") => {
            println!("Warning: Bracketing test failed (expected in CI): {}", e);
        }
        Err(e) => {
            println!("Unexpected bracketing error: {}", e);
        }
    }
}

/// Test focus stacking configuration
#[tokio::test]
async fn test_focus_stacking_legacy() {
    let device_id = TEST_DEVICE_ID.to_string();

    // Test valid stack counts
    let valid_counts = [3, 5, 10, 20];
    
    for count in valid_counts.iter() {
        let result = capture_focus_stack_legacy(device_id.clone(), *count).await;
        match result {
            Ok(frames) => {
                assert_eq!(frames.len() as u32, *count);
                for frame in frames {
                    assert!(frame.is_valid());
                }
            }
            Err(e) if e.contains("mutex") || e.contains("camera") => {
                println!("Warning: Focus stack test failed (expected in CI): {}", e);
            }
            Err(e) => {
                // Should not be validation error for valid counts
                assert!(!e.contains("Focus stack count must be"));
                println!("Unexpected focus stack error: {}", e);
            }
        }
    }

    // Test invalid stack counts
    let invalid_counts = [1, 2, 21, 50];
    
    for count in invalid_counts.iter() {
        let result = capture_focus_stack_legacy(device_id.clone(), *count).await;
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.contains("Focus stack count must be between 3 and 20"));
        }
    }
}

/// Test HDR sequence capture
#[tokio::test]
async fn test_hdr_capture() {
    let device_id = TEST_DEVICE_ID.to_string();

    let result = capture_hdr_sequence(device_id).await;
    match result {
        Ok(frames) => {
            // HDR should capture multiple frames (typically 3-5)
            assert!(frames.len() >= 3);
            assert!(frames.len() <= 7);
            
            for frame in frames {
                assert!(frame.is_valid());
                assert!(frame.size_bytes > 0);
            }
        }
        Err(e) if e.contains("mutex") || e.contains("camera") => {
            println!("Warning: HDR test failed (expected in CI): {}", e);
        }
        Err(e) => {
            println!("Unexpected HDR error: {}", e);
        }
    }
}

/// Test camera capabilities detection
#[tokio::test]
async fn test_camera_capabilities() {
    let device_id = TEST_DEVICE_ID.to_string();

    let result = test_capabilities(device_id).await;
    match result {
        Ok(capabilities) => {
            // Verify capabilities structure
            assert!(capabilities.max_resolution.0 > 0);
            assert!(capabilities.max_resolution.1 > 0);
            
            println!("Camera capabilities:");
            println!("  Manual focus: {}", capabilities.supports_manual_focus);
            println!("  Manual exposure: {}", capabilities.supports_manual_exposure);
            println!("  White balance: {}", capabilities.supports_white_balance);
            println!("  Max resolution: {}x{}", 
                capabilities.max_resolution.0, capabilities.max_resolution.1);
            println!("  Manual focus: {}", capabilities.supports_manual_focus);
        }
        Err(e) if e.contains("mutex") || e.contains("camera") => {
            println!("Warning: Capabilities test failed (expected in CI): {}", e);
        }
        Err(e) => {
            println!("Unexpected capabilities error: {}", e);
        }
    }
}

/// Test camera performance metrics
#[tokio::test]
async fn test_performance_metrics() {
    let device_id = TEST_DEVICE_ID.to_string();

    let result = get_camera_performance(device_id).await;
    match result {
        Ok(metrics) => {
            // Verify metrics structure
            assert!(metrics.capture_latency_ms >= 0.0);
            assert!(metrics.fps_actual >= 0.0);
            assert!(metrics.fps_actual >= 0.0);
            
            println!("Performance metrics:");
            println!("  Capture latency: {:.2}ms", metrics.capture_latency_ms);
            println!("  Actual FPS: {:.2}", metrics.fps_actual);
            println!("  Processing time: {:.2}ms", metrics.processing_time_ms);
            println!("  Frame drops: {}", metrics.dropped_frames);
        }
        Err(e) if e.contains("mutex") || e.contains("camera") => {
            println!("Warning: Performance test failed (expected in CI): {}", e);
        }
        Err(e) => {
            println!("Unexpected performance error: {}", e);
        }
    }
}

/// Test burst configuration parameter validation
#[tokio::test]
async fn test_burst_config_validation() {
    let device_id = TEST_DEVICE_ID.to_string();

    // Test invalid count (0)
    let invalid_config_zero = BurstConfig {
        count: 0,
        interval_ms: 100,
        bracketing: None,
        focus_stacking: false,
        auto_save: false,
        save_directory: None,
    };

    let result = capture_burst_sequence(device_id.clone(), invalid_config_zero).await;
    assert!(result.is_err());
    if let Err(e) = result {
        assert!(e.contains("Invalid burst count"));
    }

    // Test invalid count (too high)
    let invalid_config_high = BurstConfig {
        count: 100,
        interval_ms: 100,
        bracketing: None,
        focus_stacking: false,
        auto_save: false,
        save_directory: None,
    };

    let result = capture_burst_sequence(device_id, invalid_config_high).await;
    assert!(result.is_err());
    if let Err(e) = result {
        assert!(e.contains("Invalid burst count"));
    }
}

/// Performance benchmark for advanced camera operations
#[tokio::test]
async fn test_advanced_operations_performance() {
    let device_id = TEST_DEVICE_ID.to_string();

    // Benchmark controls setting speed
    let start = Instant::now();
    let controls = create_test_controls();
    
    match set_camera_controls(device_id.clone(), controls).await {
        Ok(_) => {
            let controls_time = start.elapsed();
            println!("Camera controls setting took: {:?}", controls_time);
            
            // Should be reasonably fast (under 1 second)
            assert!(controls_time < Duration::from_secs(1));
        }
        Err(e) if e.contains("mutex") || e.contains("camera") => {
            println!("Warning: Performance test skipped (no camera): {}", e);
            return;
        }
        Err(e) => {
            println!("Unexpected performance test error: {}", e);
        }
    }

    // Benchmark burst capture performance
    let start = Instant::now();
    let burst_config = BurstConfig {
        count: 5,
        interval_ms: 50, // Fast interval
        bracketing: None,
        focus_stacking: false,
        auto_save: false,
        save_directory: None,
    };

    match capture_burst_sequence(device_id, burst_config).await {
        Ok(frames) => {
            let burst_time = start.elapsed();
            println!("Burst capture ({} frames) took: {:?}", frames.len(), burst_time);
            
            // Calculate effective FPS
            let fps = frames.len() as f32 / burst_time.as_secs_f32();
            println!("Effective burst FPS: {:.2}", fps);
            
            // Should maintain reasonable performance
            assert!(fps >= 1.0); // At least 1 FPS
        }
        Err(e) if e.contains("mutex") || e.contains("camera") => {
            println!("Warning: Burst performance test skipped (no camera): {}", e);
        }
        Err(e) => {
            println!("Unexpected burst performance error: {}", e);
        }
    }
}

/// Test edge cases and boundary conditions
#[tokio::test]
async fn test_advanced_edge_cases() {
    let device_id = TEST_DEVICE_ID.to_string();

    // Test very fast intervals
    let fast_config = BurstConfig {
        count: 2,
        interval_ms: 1, // 1ms interval
        bracketing: None,
        focus_stacking: false,
        auto_save: false,
        save_directory: None,
    };

    let result = capture_burst_sequence(device_id.clone(), fast_config).await;
    match result {
        Ok(frames) => {
            assert_eq!(frames.len(), 2);
        }
        Err(e) if e.contains("mutex") || e.contains("camera") => {
            println!("Warning: Fast interval test skipped: {}", e);
        }
        Err(e) => {
            println!("Fast interval error: {}", e);
        }
    }

    // Test extreme exposure values (boundary conditions)
    let extreme_controls = CameraControls {
        exposure_time: Some(0.001), // 1ms (very fast)
        iso_sensitivity: Some(50),  // Minimum ISO
        ..CameraControls::default()
    };

    let result = set_camera_controls(device_id, extreme_controls).await;
    match result {
        Ok(_) => {
            // Should handle extreme values
        }
        Err(e) if e.contains("mutex") || e.contains("camera") => {
            println!("Warning: Extreme values test skipped: {}", e);
        }
        Err(e) => {
            println!("Extreme values error: {}", e);
        }
    }
}

/// Test concurrent advanced operations
#[tokio::test]
async fn test_concurrent_advanced_operations() {
    let device_id = TEST_DEVICE_ID.to_string();

    // Test concurrent control setting (should handle properly)
    let handles = (0..3).map(|i| {
        let device_id = device_id.clone();
        tokio::spawn(async move {
            let controls = CameraControls {
                focus_distance: Some(i as f32 * 0.3),
                ..CameraControls::default()
            };
            set_camera_controls(device_id, controls).await
        })
    }).collect::<Vec<_>>();

    let results = futures::future::join_all(handles).await;
    
    let mut success_count = 0;
    let mut expected_failures = 0;
    
    for result in results {
        match result {
            Ok(Ok(_)) => success_count += 1,
            Ok(Err(e)) if e.contains("mutex") || e.contains("camera") => {
                expected_failures += 1;
            }
            Ok(Err(e)) => {
                println!("Unexpected concurrent error: {}", e);
            }
            Err(e) => {
                println!("Task join error: {}", e);
            }
        }
    }

    // Either all should succeed or all should fail (CI)
    if success_count > 0 {
        println!("Concurrent operations succeeded: {}", success_count);
    } else {
        println!("Concurrent operations failed (expected in CI): {}", expected_failures);
    }
}

/// Test memory usage and resource cleanup in advanced operations
#[tokio::test]
async fn test_resource_management() {
    let device_id = TEST_DEVICE_ID.to_string();

    // Test multiple burst sequences to ensure proper cleanup
    for i in 0..3 {
        let config = BurstConfig {
            count: 2,
            interval_ms: 100,
            bracketing: None,
            focus_stacking: false,
            auto_save: false,
            save_directory: None,
        };

        match capture_burst_sequence(device_id.clone(), config).await {
            Ok(frames) => {
                println!("Resource test iteration {}: {} frames captured", i + 1, frames.len());
                
                // Verify frames are properly allocated
                for frame in frames {
                    assert!(!frame.data.is_empty());
                    assert!(frame.size_bytes > 0);
                }
            }
            Err(e) if e.contains("mutex") || e.contains("camera") => {
                println!("Warning: Resource test {} skipped: {}", i + 1, e);
            }
            Err(e) => {
                println!("Resource test {} error: {}", i + 1, e);
            }
        }
    }
}