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
use crate::constants::{
    DEFAULT_FORMAT_TYPE, DEFAULT_FPS, DEFAULT_RESOLUTION_HEIGHT, DEFAULT_RESOLUTION_WIDTH,
    FALLBACK_RESOLUTION_HEIGHT, FALLBACK_RESOLUTION_WIDTH, LINUX_VIDEO_DEVICE_PREFIX,
    MIN_RESOLUTION_HEIGHT, MIN_RESOLUTION_WIDTH,
};
use crate::errors::CameraError;
use crate::platform::metrics::PerfTracker;
use crate::types::{CameraDeviceInfo, CameraFormat, CameraFrame, CameraInitParams};
use nokhwa::{
    pixel_format::RgbFormat,
    query,
    utils::{RequestedFormat, RequestedFormatType},
    Camera,
};
use std::sync::{Arc, Mutex};

// Add proper imports for V4L2 format enumeration
use v4l::video::Capture;
use v4l::Device;

/// Boxed frame callback invoked for each captured frame.
type FrameCallback = Box<dyn Fn(CameraFrame) + Send + 'static>;

// Standard V4L2 control IDs (from videodev2.h).
const V4L2_CID_BRIGHTNESS: u32 = 0x0098_0900;
const V4L2_CID_CONTRAST: u32 = 0x0098_0901;
const V4L2_CID_SATURATION: u32 = 0x0098_0902;
const V4L2_CID_HUE: u32 = 0x0098_0903;
const V4L2_CID_GAMMA: u32 = 0x0098_0910;
const V4L2_CID_SHARPNESS: u32 = 0x0098_091b;
const V4L2_CID_ZOOM_ABSOLUTE: u32 = 0x009a_090d;
const V4L2_CID_FOCUS_AUTO: u32 = 0x009a_090c;
const V4L2_CID_FOCUS_ABSOLUTE: u32 = 0x009a_090a;
const V4L2_CID_EXPOSURE_AUTO: u32 = 0x009a_0901;
const V4L2_CID_EXPOSURE_ABSOLUTE: u32 = 0x009a_0902;

/// Convert a V4L2 discrete frame interval to frames-per-second.
#[allow(clippy::cast_precision_loss)]
fn interval_to_fps(numerator: u32, denominator: u32) -> f32 {
    if numerator == 0 {
        DEFAULT_FPS
    } else {
        denominator as f32 / numerator as f32
    }
}

/// List available cameras on Linux using both nokhwa for device discovery and v4l for detailed format enumeration.
///
/// # Errors
/// Returns [`CameraError::InitializationError`] if querying the V4L2 backend fails.
pub fn list_cameras() -> Result<Vec<CameraDeviceInfo>, CameraError> {
    // Queries via nokhwa first to get base list
    let cameras = query(nokhwa::utils::ApiBackend::Video4Linux)
        .map_err(|e| CameraError::InitializationError(format!("Failed to query cameras: {e}")))?;

    let mut device_list = Vec::new();
    for camera_info in cameras {
        let mut device =
            CameraDeviceInfo::new(camera_info.index().to_string(), camera_info.human_name());

        device = device.with_description(camera_info.description().to_string());

        // Use v4l crate to get real supported formats
        let mut formats = Vec::new();
        let device_index = camera_info.index().as_index().unwrap_or(0);
        let path = format!("{LINUX_VIDEO_DEVICE_PREFIX}{device_index}");

        if let Ok(dev) = Device::with_path(&path) {
            if let Ok(format_iter) = dev.enum_formats() {
                for fmt_desc in format_iter {
                    if let Ok(frames) = dev.enum_framesizes(fmt_desc.fourcc) {
                        for frame in frames {
                            let sizes = match &frame.size {
                                v4l::framesize::FrameSizeEnum::Discrete(d) => {
                                    vec![(d.width, d.height)]
                                }
                                v4l::framesize::FrameSizeEnum::Stepwise(s) => {
                                    vec![(s.max_width, s.max_height)]
                                }
                            };
                            for (width, height) in sizes {
                                if let Ok(intervals) =
                                    dev.enum_frameintervals(fmt_desc.fourcc, width, height)
                                {
                                    for interval in intervals {
                                        let fps = match &interval.interval {
                                            v4l::frameinterval::FrameIntervalEnum::Discrete(f) => {
                                                interval_to_fps(f.numerator, f.denominator)
                                            }
                                            v4l::frameinterval::FrameIntervalEnum::Stepwise(_) => {
                                                DEFAULT_FPS
                                            }
                                        };

                                        let format_str = match &fmt_desc.fourcc.repr {
                                            b"YUYV" => "YUYV",
                                            b"MJPG" => "MJPEG",
                                            b"RGB3" => "RGB",
                                            other => {
                                                std::str::from_utf8(other).unwrap_or("UNKNOWN")
                                            }
                                        }
                                        .to_string();

                                        let cf = CameraFormat::new(width, height, fps)
                                            .with_format_type(format_str);

                                        formats.push(cf);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Fallback to defaults if real enumeration failed (e.g. permission error) but warn
        if formats.is_empty() {
            log::warn!("Could not enumerate formats for {path}, using defaults");
            formats = vec![
                CameraFormat::new(
                    DEFAULT_RESOLUTION_WIDTH,
                    DEFAULT_RESOLUTION_HEIGHT,
                    DEFAULT_FPS,
                )
                .with_format_type(DEFAULT_FORMAT_TYPE.to_string()),
                CameraFormat::new(
                    FALLBACK_RESOLUTION_WIDTH,
                    FALLBACK_RESOLUTION_HEIGHT,
                    DEFAULT_FPS,
                )
                .with_format_type(DEFAULT_FORMAT_TYPE.to_string()),
                CameraFormat::new(MIN_RESOLUTION_WIDTH, MIN_RESOLUTION_HEIGHT, DEFAULT_FPS)
                    .with_format_type(DEFAULT_FORMAT_TYPE.to_string()),
            ];
        }

        device = device.with_formats(formats);
        device_list.push(device);
    }

    Ok(device_list)
}

/// Initialize camera on Linux with V4L2 backend.
///
/// # Errors
/// Returns [`CameraError::InitializationError`] if the device ID is invalid or the
/// camera cannot be opened.
pub fn initialize_camera(params: CameraInitParams) -> Result<LinuxCamera, CameraError> {
    let device_index = params
        .device_id
        .parse::<u32>()
        .map_err(|_| CameraError::InitializationError("Invalid device ID".to_string()))?;

    // Simple format request for V4L2
    let requested_format = RequestedFormat::new::<RgbFormat>(RequestedFormatType::None);

    let camera = Camera::new(
        nokhwa::utils::CameraIndex::Index(device_index),
        requested_format,
    )
    .map_err(|e| CameraError::InitializationError(format!("Failed to initialize camera: {e}")))?;

    Ok(LinuxCamera {
        camera: Arc::new(Mutex::new(camera)),
        device_id: params.device_id,
        format: params.format,
        callback: Arc::new(Mutex::new(None)),
        perf: Arc::new(Mutex::new(PerfTracker::new())),
    })
}

/// Linux-specific camera wrapper
pub struct LinuxCamera {
    camera: Arc<Mutex<Camera>>,
    device_id: String,
    format: CameraFormat,
    callback: Arc<Mutex<Option<FrameCallback>>>,
    /// Real performance tracker, updated on every capture.
    perf: Arc<Mutex<PerfTracker>>,
}

impl LinuxCamera {
    /// Capture frame from Linux camera using V4L2.
    ///
    /// # Errors
    /// Returns [`CameraError::CaptureError`] if the camera mutex is poisoned or the
    /// underlying V4L2 capture fails.
    pub fn capture_frame(&self) -> Result<CameraFrame, CameraError> {
        let mut camera = self
            .camera
            .lock()
            .map_err(|_| CameraError::CaptureError("Failed to lock camera".to_string()))?;

        let start = std::time::Instant::now();
        let frame = match camera
            .frame()
            .map_err(|e| CameraError::CaptureError(format!("Failed to capture frame: {e}")))
        {
            Ok(f) => f,
            Err(e) => {
                if let Ok(mut perf) = self.perf.lock() {
                    perf.record_drop();
                }
                return Err(e);
            }
        };
        let latency_ms = start.elapsed().as_secs_f32() * 1000.0;

        let process_start = std::time::Instant::now();
        let camera_frame = CameraFrame::new(
            frame.buffer_bytes().to_vec(),
            frame.resolution().width_x,
            frame.resolution().height_y,
            self.device_id.clone(),
        );

        let camera_frame = camera_frame.with_format(format!("{:?}", self.format));

        // Call callback if set
        if let Ok(guard) = self.callback.lock() {
            if let Some(ref cb) = *guard {
                cb(camera_frame.clone());
            }
        }
        let processing_ms = process_start.elapsed().as_secs_f32() * 1000.0;

        if let Ok(mut perf) = self.perf.lock() {
            perf.record_capture(
                latency_ms,
                processing_ms,
                Some((
                    frame.buffer_bytes().to_vec(),
                    camera_frame.width,
                    camera_frame.height,
                    format!("{:?}", self.format),
                )),
            );
        }

        Ok(camera_frame)
    }

    /// Get current format
    pub fn get_format(&self) -> &CameraFormat {
        &self.format
    }

    /// Get device ID
    pub fn get_device_id(&self) -> &str {
        &self.device_id
    }

    /// Check if camera is available
    pub fn is_available(&self) -> bool {
        self.camera.lock().is_ok_and(|c| c.is_stream_open())
    }

    /// Start camera stream.
    ///
    /// # Errors
    /// Returns [`CameraError::InitializationError`] if the camera mutex is poisoned
    /// or the stream cannot be opened.
    pub fn start_stream(&self) -> Result<(), CameraError> {
        let mut camera = self
            .camera
            .lock()
            .map_err(|_| CameraError::InitializationError("Failed to lock camera".to_string()))?;

        camera.open_stream().map_err(|e| {
            CameraError::InitializationError(format!("Failed to start stream: {e}"))
        })?;

        Ok(())
    }

    /// Stop camera stream.
    ///
    /// # Errors
    /// Returns [`CameraError::InitializationError`] if the camera mutex is poisoned
    /// or the stream cannot be stopped.
    pub fn stop_stream(&self) -> Result<(), CameraError> {
        let mut camera = self
            .camera
            .lock()
            .map_err(|_| CameraError::InitializationError("Failed to lock camera".to_string()))?;

        camera
            .stop_stream()
            .map_err(|e| CameraError::InitializationError(format!("Failed to stop stream: {e}")))?;

        Ok(())
    }

    /// Get supported V4L2 formats for this device.
    ///
    /// # Errors
    /// Returns [`CameraError::InitializationError`] if the V4L2 device cannot be opened.
    pub fn get_supported_formats(&self) -> Result<Vec<CameraFormat>, CameraError> {
        let device_index = self.device_id.parse::<usize>().unwrap_or(0);
        let path = format!("{LINUX_VIDEO_DEVICE_PREFIX}{device_index}");
        let dev = Device::with_path(&path)
            .map_err(|e| CameraError::InitializationError(format!("Failed to open device: {e}")))?;

        let mut formats = Vec::new();
        if let Ok(format_iter) = dev.enum_formats() {
            for fmt_desc in format_iter {
                if let Ok(frames) = dev.enum_framesizes(fmt_desc.fourcc) {
                    for frame in frames {
                        let sizes = match &frame.size {
                            v4l::framesize::FrameSizeEnum::Discrete(d) => {
                                vec![(d.width, d.height)]
                            }
                            v4l::framesize::FrameSizeEnum::Stepwise(s) => {
                                vec![(s.max_width, s.max_height)]
                            }
                        };
                        for (width, height) in sizes {
                            if let Ok(intervals) =
                                dev.enum_frameintervals(fmt_desc.fourcc, width, height)
                            {
                                for interval in intervals {
                                    let fps = match &interval.interval {
                                        v4l::frameinterval::FrameIntervalEnum::Discrete(f) => {
                                            interval_to_fps(f.numerator, f.denominator)
                                        }
                                        v4l::frameinterval::FrameIntervalEnum::Stepwise(_) => {
                                            DEFAULT_FPS
                                        }
                                    };
                                    let format_str = match &fmt_desc.fourcc.repr {
                                        b"YUYV" => "YUYV",
                                        b"MJPG" => "MJPEG",
                                        b"RGB3" => "RGB",
                                        other => std::str::from_utf8(other).unwrap_or("UNKNOWN"),
                                    }
                                    .to_string();
                                    formats.push(
                                        CameraFormat::new(width, height, fps)
                                            .with_format_type(format_str),
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        // Fall back to common defaults if enumeration returned nothing
        if formats.is_empty() {
            log::warn!("Could not enumerate formats for {path}, using defaults");
            formats = vec![
                CameraFormat::new(1920, 1080, 30.0).with_format_type("YUYV".to_string()),
                CameraFormat::new(1280, 720, 30.0).with_format_type("YUYV".to_string()),
                CameraFormat::new(640, 480, 30.0).with_format_type("YUYV".to_string()),
                CameraFormat::new(1920, 1080, 15.0).with_format_type("MJPEG".to_string()),
                CameraFormat::new(1280, 720, 30.0).with_format_type("MJPEG".to_string()),
            ];
        }

        Ok(formats)
    }

    /// Set camera controls (Linux V4L2 specific).
    ///
    /// # Errors
    /// Returns [`CameraError::InitializationError`] if the control is unsupported, the
    /// device cannot be opened, or the control cannot be set.
    pub fn set_control(&self, control: &str, value: i32) -> Result<(), CameraError> {
        let device_index = self.device_id.parse::<usize>().unwrap_or(0);
        let path = format!("/dev/video{device_index}");
        let dev = Device::with_path(&path)
            .map_err(|e| CameraError::InitializationError(format!("Failed to open device: {e}")))?;

        let id = match control {
            "brightness" => V4L2_CID_BRIGHTNESS,
            "contrast" => V4L2_CID_CONTRAST,
            "saturation" => V4L2_CID_SATURATION,
            "hue" => V4L2_CID_HUE,
            "gamma" => V4L2_CID_GAMMA,
            "sharpness" => V4L2_CID_SHARPNESS,
            _ => {
                return Err(CameraError::InitializationError(format!(
                    "Unsupported control: {control}"
                )))
            }
        };

        // Create control struct
        let ctrl = v4l::control::Control {
            id,
            value: v4l::control::Value::Integer(i64::from(value)),
        };

        dev.set_control(ctrl).map_err(|e| {
            CameraError::InitializationError(format!("Failed to set control {control}: {e}"))
        })?;

        Ok(())
    }

    /// Get camera controls.
    ///
    /// # Errors
    /// Returns [`CameraError`] if reading V4L2 controls fails. Returns default controls
    /// when the device cannot be opened.
    pub fn get_controls(&self) -> Result<crate::types::CameraControls, CameraError> {
        let device_index = self.device_id.parse::<usize>().unwrap_or(0);
        let path = format!("/dev/video{device_index}");

        // Return default if we can't open device (e.g. if it's busy and driver doesn't support multiple handles)
        // But we should try.
        let Ok(dev) = Device::with_path(&path) else {
            return Ok(crate::types::CameraControls::default());
        };

        // Helper to normalize value: (val - min) / (max - min)
        let get_norm = |id: u32| -> Option<f32> {
            // Query description for range
            if let Ok(controls) = dev.query_controls() {
                if let Some(desc) = controls.iter().find(|d| d.id == id) {
                    if let Ok(val) = dev.control(id) {
                        match val.value {
                            v4l::control::Value::Integer(v) => {
                                // Access min/max from description
                                let min = desc.minimum;
                                let max = desc.maximum;
                                if max > min {
                                    #[allow(clippy::cast_precision_loss)]
                                    let norm = (v - min) as f32 / (max - min) as f32;
                                    Some(norm)
                                } else {
                                    Some(0.0)
                                }
                            }
                            _ => None,
                        }
                    } else {
                        None
                    }
                } else {
                    None
                }
            } else {
                None
            }
        };

        // Helper to get raw value
        let get_val =
            |id: u32| -> Option<v4l::control::Value> { dev.control(id).map(|c| c.value).ok() };

        let auto_focus = get_val(V4L2_CID_FOCUS_AUTO).and_then(|v| match v {
            v4l::control::Value::Boolean(b) => Some(b),
            _ => None,
        });

        let auto_exposure = get_val(V4L2_CID_EXPOSURE_AUTO).and_then(|v| match v {
            v4l::control::Value::Integer(i) => Some(i != 1),
            _ => None,
        }); // 1 is manual usually

        Ok(crate::types::CameraControls {
            auto_focus,
            focus_distance: get_norm(V4L2_CID_FOCUS_ABSOLUTE),
            auto_exposure, // Boolean
            exposure_time: get_norm(V4L2_CID_EXPOSURE_ABSOLUTE),
            iso_sensitivity: None, // V4L2 ISO handling is complex/device specific
            white_balance: Some(crate::types::WhiteBalance::Auto), // Simplified
            aperture: None,
            zoom: get_norm(V4L2_CID_ZOOM_ABSOLUTE),
            brightness: get_norm(V4L2_CID_BRIGHTNESS),
            contrast: get_norm(V4L2_CID_CONTRAST),
            saturation: get_norm(V4L2_CID_SATURATION),
            sharpness: get_norm(V4L2_CID_SHARPNESS),
            noise_reduction: None,
            image_stabilization: None,
        })
    }

    /// Apply camera controls.
    ///
    /// # Errors
    /// Returns [`CameraError::InitializationError`] if the V4L2 device cannot be opened.
    pub fn apply_controls(
        &mut self,
        controls: &crate::types::CameraControls,
    ) -> Result<crate::types::ControlApplicationResult, CameraError> {
        let device_index = self.device_id.parse::<usize>().unwrap_or(0);
        let path = format!("/dev/video{device_index}");
        let dev = Device::with_path(&path).map_err(|e| {
            CameraError::InitializationError(format!("Failed to open device for controls: {e}"))
        })?;

        let mut applied = Vec::new();
        let mut rejected = Vec::new();

        // Closure returns true=applied, false=rejected
        let try_set_norm = |id: u32, val: f32| -> bool {
            if let Ok(desc_list) = dev.query_controls() {
                if let Some(desc) = desc_list.iter().find(|d| d.id == id) {
                    let min = desc.minimum;
                    let max = desc.maximum;
                    #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
                    let actual = min + (val.clamp(0.0, 1.0) * (max - min) as f32) as i64;
                    let ctrl = v4l::control::Control {
                        id,
                        value: v4l::control::Value::Integer(actual),
                    };
                    match dev.set_control(ctrl) {
                        Ok(()) => return true,
                        Err(e) => {
                            log::warn!("V4L2 set_control(id=0x{id:08x}) failed: {e}");
                        }
                    }
                } else {
                    log::warn!("V4L2 control id=0x{id:08x} not found on device");
                }
            }
            false
        };

        macro_rules! try_norm {
            ($field:expr, $id:expr, $name:literal) => {
                if let Some(v) = $field {
                    if try_set_norm($id, v) {
                        applied.push($name.to_string());
                    } else {
                        rejected.push($name.to_string());
                    }
                }
            };
        }

        try_norm!(controls.brightness, V4L2_CID_BRIGHTNESS, "brightness");
        try_norm!(controls.contrast, V4L2_CID_CONTRAST, "contrast");
        try_norm!(controls.saturation, V4L2_CID_SATURATION, "saturation");
        try_norm!(controls.sharpness, V4L2_CID_SHARPNESS, "sharpness");
        try_norm!(controls.zoom, V4L2_CID_ZOOM_ABSOLUTE, "zoom");

        if let Some(af) = controls.auto_focus {
            let ctrl = v4l::control::Control {
                id: V4L2_CID_FOCUS_AUTO,
                value: v4l::control::Value::Boolean(af),
            };
            match dev.set_control(ctrl) {
                Ok(()) => applied.push("auto_focus".to_string()),
                Err(e) => {
                    log::warn!("V4L2 set auto_focus failed: {e}");
                    rejected.push("auto_focus".to_string());
                }
            }
        }

        if let Some(fd) = controls.focus_distance {
            if controls.auto_focus != Some(true) {
                if try_set_norm(V4L2_CID_FOCUS_ABSOLUTE, fd) {
                    applied.push("focus_distance".to_string());
                } else {
                    rejected.push("focus_distance".to_string());
                }
            }
        }

        if let Some(ae) = controls.auto_exposure {
            let val = i64::from(!ae); // 1 is manual usually
            let ctrl = v4l::control::Control {
                id: V4L2_CID_EXPOSURE_AUTO,
                value: v4l::control::Value::Integer(val),
            };
            match dev.set_control(ctrl) {
                Ok(()) => applied.push("auto_exposure".to_string()),
                Err(e) => {
                    log::warn!("V4L2 set auto_exposure failed: {e}");
                    rejected.push("auto_exposure".to_string());
                }
            }
        }

        if let Some(et) = controls.exposure_time {
            if controls.auto_exposure != Some(true) {
                if try_set_norm(V4L2_CID_EXPOSURE_ABSOLUTE, et) {
                    applied.push("exposure_time".to_string());
                } else {
                    rejected.push("exposure_time".to_string());
                }
            }
        }

        Ok(crate::types::ControlApplicationResult { applied, rejected })
    }

    /// Get camera capabilities (Linux V4L2).
    ///
    /// # Errors
    /// Returns [`CameraError::InitializationError`] if the V4L2 device cannot be opened.
    pub fn test_capabilities(&self) -> Result<crate::types::CameraCapabilities, CameraError> {
        let device_index = self.device_id.parse::<usize>().unwrap_or(0);
        let path = format!("/dev/video{device_index}");
        let dev = Device::with_path(&path)
            .map_err(|e| CameraError::InitializationError(format!("Failed to open device: {e}")))?;

        let mut caps = crate::types::CameraCapabilities::default();

        // Check controls for capabilities
        if let Ok(controls) = dev.query_controls() {
            caps.supports.manual_focus = controls.iter().any(|c| c.id == V4L2_CID_FOCUS_ABSOLUTE);
            caps.supports.manual_exposure =
                controls.iter().any(|c| c.id == V4L2_CID_EXPOSURE_ABSOLUTE);
            caps.supports.zoom = controls.iter().any(|c| c.id == V4L2_CID_ZOOM_ABSOLUTE);
            caps.supports.auto_focus = controls.iter().any(|c| c.id == V4L2_CID_FOCUS_AUTO);
            caps.supports.auto_exposure = controls.iter().any(|c| c.id == V4L2_CID_EXPOSURE_AUTO);
        }

        // Get actual ranges/resolutions if possible (requires more complex enumeration)
        if let Ok(formats) = self.get_supported_formats() {
            if let Some(max) = formats
                .iter()
                .max_by_key(|f| u64::from(f.width) * u64::from(f.height))
            {
                caps.max_resolution = (max.width, max.height);
                caps.max_fps = max.fps;
            }
        }

        Ok(caps)
    }

    /// Get real performance metrics for this camera session.
    ///
    /// # Errors
    /// Returns [`CameraError::CaptureError`] if the shared perf tracker mutex is
    /// poisoned.
    pub fn get_performance_metrics(
        &self,
    ) -> Result<crate::types::CameraPerformanceMetrics, CameraError> {
        let perf = self
            .perf
            .lock()
            .map_err(|_| CameraError::CaptureError("Perf tracker mutex poisoned".to_string()))?;
        Ok(crate::platform::metrics::build_metrics(
            &perf,
            &self.device_id,
        ))
    }

    /// Set frame callback for real-time processing.
    ///
    /// # Errors
    /// Returns [`CameraError::InitializationError`] if the callback mutex is poisoned.
    pub fn set_callback<F>(&self, callback: F) -> Result<(), CameraError>
    where
        F: Fn(CameraFrame) + Send + 'static,
    {
        let mut guard = self
            .callback
            .lock()
            .map_err(|_| CameraError::InitializationError("Callback mutex poisoned".to_string()))?;
        *guard = Some(Box::new(callback));
        Ok(())
    }
}

// Ensure the camera is properly cleaned up
impl Drop for LinuxCamera {
    fn drop(&mut self) {
        if let Ok(mut camera) = self.camera.lock() {
            let _ = camera.stop_stream();
        }
    }
}

// Thread-safe implementation
unsafe impl Send for LinuxCamera {}
unsafe impl Sync for LinuxCamera {}

/// Linux-specific utilities
pub mod utils {
    use super::CameraError;

    /// Check if V4L2 is available on the system
    pub fn is_v4l2_available() -> bool {
        std::path::Path::new("/dev/video0").exists()
    }

    /// List all V4L2 devices in /dev/video*.
    ///
    /// # Errors
    /// Currently infallible, but returns [`CameraError`] for API consistency.
    pub fn list_v4l2_devices() -> Result<Vec<String>, CameraError> {
        let mut devices = Vec::new();

        for i in 0..10 {
            // Check video0 through video9
            let device_path = format!("/dev/video{i}");
            if std::path::Path::new(&device_path).exists() {
                devices.push(device_path);
            }
        }

        Ok(devices)
    }

    /// Get V4L2 device capabilities.
    ///
    /// # Errors
    /// Currently infallible, but returns [`CameraError`] for API consistency.
    pub fn get_device_caps(_device_path: &str) -> Result<Vec<String>, CameraError> {
        // This would typically query V4L2 capabilities
        // For now, return common capabilities
        Ok(vec![
            "Video Capture".to_string(),
            "Streaming".to_string(),
            "Extended Controls".to_string(),
        ])
    }
}