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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
use crate::commands::capture::get_or_create_camera;
use crate::constants::{MAX_ISO, MIN_ISO};
use crate::platform::PlatformCamera;
use crate::types::{
    BurstConfig, CameraControls, CameraFrame, ControlApplicationResult, WhiteBalance,
};
use std::sync::{Arc, Mutex as StdMutex};
use std::time::Instant;
use tauri::command;

/// Apply advanced camera controls
///
/// # Errors
/// Returns an `Err` if the camera cannot be created or retrieved, if the
/// camera mutex is poisoned, if the blocking task fails to join, or if
/// applying the controls to the camera fails.
#[command]
pub async fn set_camera_controls(
    device_id: String,
    controls: CameraControls,
) -> Result<ControlApplicationResult, String> {
    log::info!("Setting camera controls for device: {device_id}");

    let camera_arc =
        get_or_create_camera(device_id.clone(), crate::types::CameraFormat::standard()).await?;

    let device_id_clone = device_id.clone();
    tokio::task::spawn_blocking(move || {
        let mut camera = camera_arc
            .lock()
            .map_err(|_| "Mutex poisoned".to_string())?;

        let result = camera.apply_controls(&controls).map_err(|e| {
            log::error!("Failed to apply camera controls: {e}");
            format!("Failed to apply controls: {e}")
        })?;

        log::info!(
            "Camera controls applied for device {} (applied={}, rejected={})",
            device_id_clone,
            result.applied.len(),
            result.rejected.len()
        );

        Ok(result)
    })
    .await
    .map_err(|e| format!("Task join error: {e}"))?
}

/// Get current camera controls
///
/// # Errors
/// Returns an `Err` if the camera cannot be obtained, if the camera mutex
/// is poisoned, if the blocking task fails to join, or if reading the
/// controls from the camera fails.
#[command]
pub async fn get_camera_controls(device_id: String) -> Result<CameraControls, String> {
    log::info!("Getting camera controls for device: {device_id}");

    let camera_arc =
        get_or_create_camera(device_id.clone(), crate::types::CameraFormat::standard()).await?;

    let device_id_clone = device_id.clone();
    tokio::task::spawn_blocking(move || {
        let camera = camera_arc
            .lock()
            .map_err(|_| "Mutex poisoned".to_string())?;

        match camera.get_controls() {
            Ok(controls) => {
                log::debug!("Retrieved camera controls for device: {device_id_clone}");
                Ok(controls)
            }
            Err(e) => {
                log::error!("Failed to get camera controls: {e}");
                Err(format!("Failed to get controls: {e}"))
            }
        }
    })
    .await
    .map_err(|e| format!("Task join error: {e}"))?
}

/// Capture burst sequence with advanced controls
///
/// # Errors
/// Returns an `Err` if `config.count` is `0` or greater than `50`, if focus
/// stacking is requested with fewer than `2` frames, or if exposure
/// bracketing is misconfigured (empty stops or a non-positive base
/// exposure). Also returns an `Err` if the camera cannot be obtained, the
/// mutex is poisoned, the blocking task fails to join, a frame capture
/// fails, or an auto-save fails.
#[command]
pub async fn capture_burst_sequence(
    device_id: String,
    config: BurstConfig,
) -> Result<Vec<CameraFrame>, String> {
    log::info!(
        "Starting burst capture: {} frames from device {}",
        config.count,
        device_id
    );

    validate_burst_config(&config)?;

    let camera_arc =
        get_or_create_camera(device_id.clone(), crate::types::CameraFormat::hd()).await?;

    start_burst_stream(camera_arc.clone()).await?;

    let mut frames = Vec::with_capacity(config.count as usize);
    let start_time = Instant::now();

    for i in 0..config.count {
        log::debug!("Capturing burst frame {} of {}", i + 1, config.count);

        let frame = capture_burst_frame(camera_arc.clone(), config.clone(), i).await?;
        frames.push(frame);

        // Wait between captures (except for the last one)
        if i < config.count - 1 {
            tokio::time::sleep(tokio::time::Duration::from_millis(u64::from(
                config.interval_ms,
            )))
            .await;
        }
    }

    let total_time = start_time.elapsed();
    #[allow(clippy::cast_precision_loss)]
    // usize→f32: frame count is capped at 50, no precision loss at this scale
    let burst_fps = frames.len() as f32 / total_time.as_secs_f32();
    log::info!(
        "Burst capture completed: {} frames in {:?} ({:.2} fps)",
        frames.len(),
        total_time,
        burst_fps
    );

    // Auto-save if configured
    if config.auto_save {
        if let Some(ref save_dir) = config.save_directory {
            save_burst_sequence(&frames, save_dir).await?;
        }
    }

    Ok(frames)
}

/// Validate a [`BurstConfig`] prior to starting a burst capture.
fn validate_burst_config(config: &BurstConfig) -> Result<(), String> {
    if config.count == 0 || config.count > 50 {
        return Err("Invalid burst count (must be 1-50)".to_string());
    }

    if config.focus_stacking && config.count < 2 {
        return Err("Focus stacking requires at least 2 frames (count >= 2)".to_string());
    }

    if let Some(ref bracketing) = config.bracketing {
        if bracketing.stops.is_empty() {
            return Err("Exposure bracketing requires at least one stop value".to_string());
        }
        if bracketing.base_exposure <= 0.0 {
            return Err("Exposure bracketing base_exposure must be greater than zero".to_string());
        }
    }

    Ok(())
}

/// Start the camera stream on a blocking task, logging (not erroring) on failure.
async fn start_burst_stream(camera_arc: Arc<StdMutex<PlatformCamera>>) -> Result<(), String> {
    tokio::task::spawn_blocking(move || {
        if let Ok(mut camera) = camera_arc.lock() {
            if let Err(e) = camera.start_stream() {
                log::warn!("Failed to start camera stream: {e}");
            }
        }
    })
    .await
    .map_err(|e| format!("Task join error: {e}"))
}

/// Capture a single burst frame, applying exposure bracketing and focus stacking
/// controls as configured for the given frame `index`.
async fn capture_burst_frame(
    camera_arc: Arc<StdMutex<PlatformCamera>>,
    config: BurstConfig,
    index: u32,
) -> Result<CameraFrame, String> {
    tokio::task::spawn_blocking(move || {
        let mut camera = camera_arc
            .lock()
            .map_err(|_| "Mutex poisoned".to_string())?;

        // Apply exposure bracketing if configured
        if let Some(ref bracketing) = config.bracketing {
            if let Some(stop) = bracketing
                .stops
                .get(index as usize % bracketing.stops.len())
            {
                let exposure_time = bracketing.base_exposure * 2.0_f32.powf(*stop);
                let controls = CameraControls {
                    auto_exposure: Some(false),
                    exposure_time: Some(exposure_time),
                    ..CameraControls::default()
                };

                if let Err(e) = camera.apply_controls(&controls) {
                    log::warn!("Failed to apply exposure bracketing: {e}");
                }
            }
        }

        // Apply focus stacking if configured
        if config.focus_stacking {
            #[allow(clippy::cast_precision_loss)]
            // u32→f32: index and count are small (< 50), exact in f32
            let focus_distance = index as f32 / (config.count as f32 - 1.0); // 0.0 to 1.0
            let controls = CameraControls {
                auto_focus: Some(false),
                focus_distance: Some(focus_distance),
                ..CameraControls::default()
            };

            if let Err(e) = camera.apply_controls(&controls) {
                log::warn!("Failed to apply focus stacking: {e}");
            }

            // Wait for focus adjustment (blocking sleep is okay here as we are in spawn_blocking)
            std::thread::sleep(std::time::Duration::from_millis(200));
        }

        // Capture frame with performance monitoring
        let capture_start = Instant::now();
        match camera.capture_frame() {
            Ok(mut frame) => {
                let capture_time = capture_start.elapsed();

                // Add performance metadata
                frame.metadata.capture_settings = camera.get_controls().ok();

                log::debug!("Burst frame {} captured in {:?}", index + 1, capture_time);
                Ok(frame)
            }
            Err(e) => {
                log::error!("Failed to capture burst frame {}: {}", index + 1, e);
                Err(format!(
                    "Failed to capture burst frame {}: {}",
                    index + 1,
                    e
                ))
            }
        }
    })
    .await
    .map_err(|e| format!("Task join error: {e}"))?
}

/// Batch camera settings to apply in a single call
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CameraSettingsInput {
    /// Camera device identifier
    pub device_id: String,
    /// Manual focus distance (0.0 = infinity, 1.0 = closest)
    pub focus_distance: Option<f32>,
    /// Exposure time in seconds (0.0 < t <= 10.0)
    pub exposure_time: Option<f32>,
    /// ISO sensitivity (50-12800)
    pub iso_sensitivity: Option<u32>,
    /// White balance mode
    pub white_balance: Option<WhiteBalance>,
    /// Full `CameraControls` struct (merged over individual settings)
    pub controls: Option<CameraControls>,
}

/// Apply multiple camera settings at once.
///
/// This is the preferred entry point for setting camera controls.
/// It merges individual settings (focus, exposure, ISO, white balance)
/// with an optional `CameraControls` struct and applies them in a single
/// call. Individual granular commands (`set_manual_focus`,
/// `set_manual_exposure`, `set_white_balance`) remain available for
/// backward compatibility.
///
/// # Errors
/// Returns an `Err` if `focus_distance` is outside `[0.0, 1.0]`,
/// `exposure_time` is outside `(0.0, 10.0]`, or `iso_sensitivity` is
/// outside the supported range. Otherwise propagates any error from
/// [`set_camera_controls`].
#[command]
pub async fn apply_camera_settings(
    settings: CameraSettingsInput,
) -> Result<ControlApplicationResult, String> {
    let mut combined = CameraControls::default();

    if let Some(focus_distance) = settings.focus_distance {
        if !(0.0..=1.0).contains(&focus_distance) {
            return Err("Focus distance must be between 0.0 and 1.0".to_string());
        }
        combined.auto_focus = Some(false);
        combined.focus_distance = Some(focus_distance);
    }

    if let Some(exposure_time) = settings.exposure_time {
        if exposure_time <= 0.0 || exposure_time > 10.0 {
            return Err("Exposure time must be between 0.0 and 10.0 seconds".to_string());
        }
        combined.auto_exposure = Some(false);
        combined.exposure_time = Some(exposure_time);
    }

    if let Some(iso_sensitivity) = settings.iso_sensitivity {
        if !(MIN_ISO..=MAX_ISO).contains(&iso_sensitivity) {
            return Err(format!(
                "ISO sensitivity must be between {MIN_ISO} and {MAX_ISO}"
            ));
        }
        combined.auto_exposure = Some(false);
        combined.iso_sensitivity = Some(iso_sensitivity);
    }

    if let Some(white_balance) = settings.white_balance {
        combined.white_balance = Some(white_balance);
    }

    if let Some(controls) = &settings.controls {
        if controls.auto_focus.is_some() {
            combined.auto_focus = controls.auto_focus;
        }
        if controls.focus_distance.is_some() {
            combined.focus_distance = controls.focus_distance;
        }
        if controls.auto_exposure.is_some() {
            combined.auto_exposure = controls.auto_exposure;
        }
        if controls.exposure_time.is_some() {
            combined.exposure_time = controls.exposure_time;
        }
        if controls.iso_sensitivity.is_some() {
            combined.iso_sensitivity = controls.iso_sensitivity;
        }
        if controls.white_balance.is_some() {
            combined.white_balance.clone_from(&controls.white_balance);
        }
    }

    set_camera_controls(settings.device_id, combined).await
}

/// Enable manual focus mode and set focus distance
///
/// ## Deprecation
/// Prefer the consolidated [`apply_camera_settings`] command
/// which can batch multiple settings in a single call.
///
/// # Errors
/// Returns an `Err` if `focus_distance` is outside `[0.0, 1.0]`.
/// Otherwise propagates any error from [`set_camera_controls`].
#[command]
pub async fn set_manual_focus(
    device_id: String,
    focus_distance: f32,
) -> Result<ControlApplicationResult, String> {
    if !(0.0..=1.0).contains(&focus_distance) {
        return Err("Focus distance must be between 0.0 (infinity) and 1.0 (closest)".to_string());
    }

    let controls = CameraControls {
        auto_focus: Some(false),
        focus_distance: Some(focus_distance),
        ..CameraControls::default()
    };

    set_camera_controls(device_id, controls).await
}

/// Set manual exposure settings
///
/// ## Deprecation
/// Prefer the consolidated [`apply_camera_settings`] command
/// which can batch multiple settings in a single call.
///
/// # Errors
/// Returns an `Err` if `exposure_time` is outside `(0.0, 10.0]` or if
/// `iso_sensitivity` is outside the supported range. Otherwise propagates
/// any error from [`set_camera_controls`].
#[command]
pub async fn set_manual_exposure(
    device_id: String,
    exposure_time: f32,
    iso_sensitivity: u32,
) -> Result<ControlApplicationResult, String> {
    if exposure_time <= 0.0 || exposure_time > 10.0 {
        return Err("Exposure time must be between 0.0 and 10.0 seconds".to_string());
    }

    if !(MIN_ISO..=MAX_ISO).contains(&iso_sensitivity) {
        return Err(format!(
            "ISO sensitivity must be between {MIN_ISO} and {MAX_ISO}"
        ));
    }

    let controls = CameraControls {
        auto_exposure: Some(false),
        exposure_time: Some(exposure_time),
        iso_sensitivity: Some(iso_sensitivity),
        ..CameraControls::default()
    };

    set_camera_controls(device_id, controls).await
}

/// Set white balance mode
///
/// ## Deprecation
/// Prefer the consolidated [`apply_camera_settings`] command
/// which can batch multiple settings in a single call.
///
/// # Errors
/// Propagates any error from [`set_camera_controls`].
#[command]
pub async fn set_white_balance(
    device_id: String,
    white_balance: WhiteBalance,
) -> Result<ControlApplicationResult, String> {
    let controls = CameraControls {
        white_balance: Some(white_balance),
        ..CameraControls::default()
    };

    set_camera_controls(device_id, controls).await
}

/// Enable HDR mode with automatic exposure bracketing
///
/// # Errors
/// Propagates any error from [`capture_burst_sequence`] (including invalid
/// burst configuration) or from obtaining the camera.
#[command]
pub async fn capture_hdr_sequence(device_id: String) -> Result<Vec<CameraFrame>, String> {
    log::info!("Capturing HDR sequence from device: {device_id}");

    let config = BurstConfig::hdr_burst();
    capture_burst_sequence(device_id, config).await
}

/// Capture focus stacked sequence for macro photography (legacy - use `focus_stack` module)
///
/// # Errors
/// Returns an `Err` if `stack_count` is outside `3..=20`. Otherwise
/// propagates any error from [`capture_burst_sequence`] or from obtaining
/// the camera.
#[command]
pub async fn capture_focus_stack_legacy(
    device_id: String,
    stack_count: u32,
) -> Result<Vec<CameraFrame>, String> {
    log::info!("Capturing focus stack (legacy): {stack_count} frames from device {device_id}");

    if !(3..=20).contains(&stack_count) {
        return Err("Focus stack count must be between 3 and 20".to_string());
    }

    let config = BurstConfig {
        count: stack_count,
        interval_ms: 1000, // 1 second between focus adjustments
        bracketing: None,
        focus_stacking: true,
        auto_save: true,
        save_directory: Some("focus_stack".to_string()),
    };

    capture_burst_sequence(device_id, config).await
}

/// Get camera performance metrics
///
/// # Errors
/// Returns an `Err` if the camera cannot be obtained, if the camera mutex
/// is poisoned, if the blocking task fails to join, or if reading the
/// performance metrics from the camera fails.
#[command]
pub async fn get_camera_performance(
    device_id: String,
) -> Result<crate::types::CameraPerformanceMetrics, String> {
    let camera_arc =
        get_or_create_camera(device_id.clone(), crate::types::CameraFormat::standard()).await?;

    let device_id_clone = device_id.clone();
    tokio::task::spawn_blocking(move || {
        let camera = camera_arc
            .lock()
            .map_err(|_| "Mutex poisoned".to_string())?;

        match camera.get_performance_metrics() {
            Ok(metrics) => {
                log::debug!(
                    "Performance metrics for {}: {:.2}ms latency, {:.2} fps",
                    device_id_clone,
                    metrics.capture_latency_ms,
                    metrics.fps_actual
                );
                Ok(metrics)
            }
            Err(e) => {
                log::error!("Failed to get performance metrics: {e}");
                Err(format!("Failed to get performance metrics: {e}"))
            }
        }
    })
    .await
    .map_err(|e| format!("Task join error: {e}"))?
}

/// Test camera capabilities and return supported features
///
/// # Errors
/// Returns an `Err` if the camera cannot be obtained, if the camera mutex
/// is poisoned, if the blocking task fails to join, or if querying the
/// camera capabilities fails.
#[command]
pub async fn test_camera_capabilities(
    device_id: String,
) -> Result<crate::types::CameraCapabilities, String> {
    log::info!("Testing camera capabilities for device: {device_id}");

    let camera_arc =
        get_or_create_camera(device_id.clone(), crate::types::CameraFormat::standard()).await?;

    let device_id_clone = device_id.clone();
    tokio::task::spawn_blocking(move || {
        let camera = camera_arc
            .lock()
            .map_err(|_| "Mutex poisoned".to_string())?;

        match camera.test_capabilities() {
            Ok(capabilities) => {
                log::info!(
                    "Camera {} capabilities: manual_focus={}, manual_exposure={}, max_res={}x{}",
                    device_id_clone,
                    capabilities.supports.manual_focus,
                    capabilities.supports.manual_exposure,
                    capabilities.max_resolution.0,
                    capabilities.max_resolution.1
                );
                Ok(capabilities)
            }
            Err(e) => {
                log::error!("Failed to test camera capabilities: {e}");
                Err(format!("Failed to test capabilities: {e}"))
            }
        }
    })
    .await
    .map_err(|e| format!("Task join error: {e}"))?
}

// Helper functions

/// Save burst sequence to disk
async fn save_burst_sequence(frames: &[CameraFrame], save_dir: &str) -> Result<(), String> {
    log::info!("Saving {} frames to directory: {}", frames.len(), save_dir);

    // Create directory if it doesn't exist
    if let Err(e) = tokio::fs::create_dir_all(save_dir).await {
        return Err(format!("Failed to create directory {save_dir}: {e}"));
    }

    let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");

    // Save each frame
    for (i, frame) in frames.iter().enumerate() {
        let filename = format!("{}/burst_{}_{:03}.jpg", save_dir, timestamp, i + 1);

        // Convert to JPEG for smaller file size
        let img = image::RgbImage::from_vec(frame.width, frame.height, frame.data.clone())
            .ok_or_else(|| "Failed to create image from frame data".to_string())?;

        let dynamic_img = image::DynamicImage::ImageRgb8(img);

        // Save with compression in a spawn_blocking task
        let filename_clone = filename.clone();
        match tokio::task::spawn_blocking(move || {
            dynamic_img.save_with_format(&filename_clone, image::ImageFormat::Jpeg)
        })
        .await
        {
            Ok(Ok(())) => {
                log::debug!("Saved frame {} to {}", i + 1, filename);
            }
            Ok(Err(e)) => {
                log::error!("Failed to save frame {}: {}", i + 1, e);
                return Err(format!("Failed to save frame {}: {}", i + 1, e));
            }
            Err(e) => {
                log::error!("Task join error for frame {}: {}", i + 1, e);
                return Err(format!("Failed to save frame {}: task error", i + 1));
            }
        }
    }

    log::info!("Successfully saved {} frames to {}", frames.len(), save_dir);
    Ok(())
}

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

    fn enable_mock_camera() {
        std::env::set_var("CRABCAMERA_USE_MOCK", "1");
    }

    #[tokio::test]
    async fn test_set_manual_focus_rejects_out_of_range_value() {
        let result = set_manual_focus("0".to_string(), 1.5).await;
        assert!(result.is_err());
        assert!(result
            .err()
            .unwrap_or_default()
            .contains("Focus distance must be between 0.0"));
    }

    #[tokio::test]
    async fn test_set_manual_exposure_rejects_invalid_exposure_time() {
        let result = set_manual_exposure("0".to_string(), 0.0, MIN_ISO).await;
        assert!(result.is_err());
        assert!(result
            .err()
            .unwrap_or_default()
            .contains("Exposure time must be between 0.0 and 10.0 seconds"));
    }

    #[tokio::test]
    async fn test_set_manual_exposure_rejects_invalid_iso() {
        let result = set_manual_exposure("0".to_string(), 0.01, MIN_ISO.saturating_sub(1)).await;
        assert!(result.is_err());
        assert!(result
            .err()
            .unwrap_or_default()
            .contains("ISO sensitivity must be between"));
    }

    #[tokio::test]
    async fn test_apply_camera_settings_batches_correctly() {
        let result = apply_camera_settings(CameraSettingsInput {
            device_id: "0".to_string(),
            focus_distance: Some(1.5),
            exposure_time: None,
            iso_sensitivity: None,
            white_balance: None,
            controls: None,
        })
        .await;
        assert!(result.is_err());
        assert!(result
            .expect_err("focus distance error expected")
            .contains("Focus distance must be between 0.0"));

        let result = apply_camera_settings(CameraSettingsInput {
            device_id: "0".to_string(),
            focus_distance: None,
            exposure_time: Some(0.0),
            iso_sensitivity: None,
            white_balance: None,
            controls: None,
        })
        .await;
        assert!(result.is_err());
        assert!(result
            .expect_err("exposure time error expected")
            .contains("Exposure time must be between 0.0 and 10.0 seconds"));

        let result = apply_camera_settings(CameraSettingsInput {
            device_id: "0".to_string(),
            focus_distance: None,
            exposure_time: None,
            iso_sensitivity: Some(MIN_ISO.saturating_sub(1)),
            white_balance: None,
            controls: None,
        })
        .await;
        assert!(result.is_err());
        assert!(result
            .expect_err("ISO sensitivity error expected")
            .contains("ISO sensitivity must be between"));
    }

    #[tokio::test]
    async fn test_capture_burst_sequence_rejects_invalid_count() {
        let config = BurstConfig {
            count: 0,
            interval_ms: 10,
            bracketing: None,
            focus_stacking: false,
            auto_save: false,
            save_directory: None,
        };

        let result = capture_burst_sequence("0".to_string(), config).await;
        assert!(result.is_err());
        assert!(result
            .err()
            .unwrap_or_default()
            .contains("Invalid burst count"));
    }

    #[tokio::test]
    async fn test_capture_burst_sequence_rejects_invalid_focus_stacking_count() {
        let config = BurstConfig {
            count: 1,
            interval_ms: 10,
            bracketing: None,
            focus_stacking: true,
            auto_save: false,
            save_directory: None,
        };

        let result = capture_burst_sequence("0".to_string(), config).await;
        assert!(result.is_err());
        assert!(result
            .err()
            .unwrap_or_default()
            .contains("Focus stacking requires at least 2 frames"));
    }

    #[tokio::test]
    async fn test_capture_burst_sequence_rejects_empty_bracketing_stops() {
        let config = BurstConfig {
            count: 3,
            interval_ms: 10,
            bracketing: Some(ExposureBracketing {
                stops: vec![],
                base_exposure: 0.01,
            }),
            focus_stacking: false,
            auto_save: false,
            save_directory: None,
        };

        let result = capture_burst_sequence("0".to_string(), config).await;
        assert!(result.is_err());
        assert!(result
            .err()
            .unwrap_or_default()
            .contains("Exposure bracketing requires at least one stop value"));
    }

    #[tokio::test]
    async fn test_capture_burst_sequence_rejects_non_positive_base_exposure() {
        let config = BurstConfig {
            count: 3,
            interval_ms: 10,
            bracketing: Some(ExposureBracketing {
                stops: vec![-1.0, 0.0, 1.0],
                base_exposure: 0.0,
            }),
            focus_stacking: false,
            auto_save: false,
            save_directory: None,
        };

        let result = capture_burst_sequence("0".to_string(), config).await;
        assert!(result.is_err());
        assert!(result
            .err()
            .unwrap_or_default()
            .contains("Exposure bracketing base_exposure must be greater than zero"));
    }

    #[tokio::test]
    async fn test_capture_focus_stack_legacy_rejects_out_of_range_stack_count() {
        let result = capture_focus_stack_legacy("0".to_string(), 2).await;
        assert!(result.is_err());
        assert!(result
            .err()
            .unwrap_or_default()
            .contains("Focus stack count must be between 3 and 20"));
    }

    #[tokio::test]
    async fn test_save_burst_sequence_rejects_invalid_frame_data_shape() {
        let invalid_frame = CameraFrame::new(vec![1, 2, 3], 16, 16, "0".to_string());
        let result = save_burst_sequence(&[invalid_frame], "test_outputs/invalid_burst").await;

        assert!(result.is_err());
        assert!(result
            .err()
            .unwrap_or_default()
            .contains("Failed to create image from frame data"));
    }

    #[tokio::test]
    async fn test_get_and_set_camera_controls_with_mock() {
        enable_mock_camera();

        let controls = CameraControls {
            auto_focus: Some(true),
            brightness: Some(0.1),
            ..Default::default()
        };

        let apply = set_camera_controls("0".to_string(), controls)
            .await
            .expect("set controls should succeed with mock");
        assert!(!apply.applied.is_empty());

        let fetched = get_camera_controls("0".to_string())
            .await
            .expect("get controls should succeed with mock");
        assert_eq!(fetched.auto_focus, Some(true));

        std::env::remove_var("CRABCAMERA_USE_MOCK");
    }

    #[tokio::test]
    async fn test_capture_burst_sequence_success_with_mock() {
        enable_mock_camera();

        let config = BurstConfig {
            count: 2,
            interval_ms: 0,
            bracketing: None,
            focus_stacking: false,
            auto_save: false,
            save_directory: None,
        };

        let frames = capture_burst_sequence("0".to_string(), config)
            .await
            .expect("burst capture should succeed with mock");
        assert_eq!(frames.len(), 2);

        std::env::remove_var("CRABCAMERA_USE_MOCK");
    }

    #[tokio::test]
    async fn test_performance_and_capabilities_with_mock() {
        enable_mock_camera();

        let metrics = get_camera_performance("0".to_string())
            .await
            .expect("performance should succeed");
        assert!(metrics.fps_actual > 0.0);

        let caps = test_camera_capabilities("0".to_string())
            .await
            .expect("capabilities should succeed");
        assert!(caps.supports.manual_focus);

        std::env::remove_var("CRABCAMERA_USE_MOCK");
    }

    #[tokio::test]
    async fn test_wrapper_commands_hdr_focus_legacy_and_white_balance() {
        enable_mock_camera();

        let wb = set_white_balance("0".to_string(), WhiteBalance::Daylight)
            .await
            .expect("set_white_balance should succeed with mock");
        assert!(!wb.applied.is_empty());

        let hdr = capture_hdr_sequence("0".to_string())
            .await
            .expect("hdr wrapper should succeed with mock");
        assert!(!hdr.is_empty());

        let stack = capture_focus_stack_legacy("0".to_string(), 3)
            .await
            .expect("focus stack legacy should succeed with mock");
        assert_eq!(stack.len(), 3);

        std::env::remove_var("CRABCAMERA_USE_MOCK");
    }
}