camera-rs 0.5.0

Intent-driven cross-platform camera capture with bounded native frames
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
//! FFI bindings for the libuvc C library.

use libc::{c_char, c_int, c_void, size_t, timespec, timeval};

// ============================================================================
// Error codes.
// ============================================================================

pub type UvcError = c_int;

pub const UVC_SUCCESS: UvcError = 0;
pub const UVC_ERROR_IO: UvcError = -1;
pub const UVC_ERROR_INVALID_PARAM: UvcError = -2;
pub const UVC_ERROR_ACCESS: UvcError = -3;
pub const UVC_ERROR_NO_DEVICE: UvcError = -4;
pub const UVC_ERROR_NOT_FOUND: UvcError = -5;
pub const UVC_ERROR_BUSY: UvcError = -6;
pub const UVC_ERROR_TIMEOUT: UvcError = -7;
pub const UVC_ERROR_OVERFLOW: UvcError = -8;
pub const UVC_ERROR_PIPE: UvcError = -9;
pub const UVC_ERROR_INTERRUPTED: UvcError = -10;
pub const UVC_ERROR_NO_MEM: UvcError = -11;
pub const UVC_ERROR_NOT_SUPPORTED: UvcError = -12;

// ============================================================================
// Frame format values. These must match enum uvc_frame_format in
// libuvc/include/libuvc/libuvc.h and are verified by the C ABI probe.
//   UNKNOWN=0, UNCOMPRESSED=1, COMPRESSED=2, YUYV=3, UYVY=4,
//   RGB=5, BGR=6, MJPEG=7, H264=8, GRAY8=9, GRAY16=10
// ============================================================================

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UvcFrameFormat {
    Unknown = 0,
    // Any = 0,  // Same value as Unknown.
    Uncompressed = 1,
    Compressed = 2,
    Yuyv = 3,
    Uyvy = 4,
    Rgb = 5,
    Bgr = 6,
    Mjpeg = 7,
    H264 = 8,
    Gray8 = 9,
    Gray16 = 10,
    // Bayer formats.
    By8 = 11,
    Ba81 = 12,
    Sgrbg8 = 13,
    Sgbrg8 = 14,
    Srggb8 = 15,
    Sbggr8 = 16,
    // YUV420
    Nv12 = 17,
    P010 = 18,
    // Count sentinel used for bounds checking.
    // Count = 19,
}

// ============================================================================
// UVC request codes.
// ============================================================================

#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UvcReqCode {
    Undefined = 0x00,
    SetCur = 0x01,
    GetCur = 0x81,
    GetMin = 0x82,
    GetMax = 0x83,
    GetRes = 0x84,
    GetLen = 0x85,
    GetInfo = 0x86,
    GetDef = 0x87,
}

// ============================================================================
// Opaque structure declarations.
// ============================================================================

#[repr(C)]
pub struct UvcContext {
    _private: [u8; 0],
}

#[repr(C)]
pub struct UvcDevice {
    _private: [u8; 0],
}

#[repr(C)]
pub struct UvcDeviceHandle {
    _private: [u8; 0],
}

/// Stream control structure.
/// Must exactly match libuvc's `uvc_stream_ctrl_t`.
/// The C ABI probe verifies its 40-byte size.
#[repr(C)]
pub struct UvcStreamCtrl {
    pub bm_hint: u16,            // offset 0
    pub b_format_index: u8,      // offset 2
    pub b_frame_index: u8,       // offset 3
    pub dw_frame_interval: u32,  // offset 4
    pub w_key_frame_rate: u16,   // offset 8
    pub w_p_frame_rate: u16,     // offset 10
    pub w_comp_quality: u16,     // offset 12
    pub w_comp_window_size: u16, // offset 14
    pub w_delay: u16,            // offset 16
    // implicit 2-byte padding here        // offset 18-19
    pub dw_max_video_frame_size: u32,      // offset 20
    pub dw_max_payload_transfer_size: u32, // offset 24
    pub dw_clock_frequency: u32,           // offset 28
    pub bm_framing_info: u8,               // offset 32
    pub b_preferred_version: u8,           // offset 33
    pub b_min_version: u8,                 // offset 34
    pub b_max_version: u8,                 // offset 35
    pub b_interface_number: u8,            // offset 36
                                           // implicit 3-byte tail padding        // offset 37-39
}

#[repr(C)]
pub struct LibusbContext {
    _private: [u8; 0],
}

// ============================================================================
// Format and frame descriptors.
// ============================================================================

#[repr(C)]
pub struct UvcFormatDesc {
    pub parent: *mut c_void,
    pub prev: *mut UvcFormatDesc,
    pub next: *mut UvcFormatDesc,
    pub b_descriptor_subtype: u32, // enum in C is 4 bytes
    pub b_format_index: u8,
    pub b_num_frame_descriptors: u8,
    pub guid_format: [u8; 16],
    pub b_bits_per_pixel: u8,
    pub b_default_frame_index: u8,
    pub b_aspect_ratio_x: u8,
    pub b_aspect_ratio_y: u8,
    pub bm_interlace_flags: u8,
    pub b_copy_protect: u8,
    pub b_variable_size: u8,
    pub frame_descs: *mut UvcFrameDesc,
    pub still_frame_desc: *mut c_void,
}

#[repr(C)]
pub struct UvcFrameDesc {
    pub parent: *mut UvcFormatDesc,
    pub prev: *mut UvcFrameDesc,
    pub next: *mut UvcFrameDesc,
    pub b_descriptor_subtype: u32, // enum in C is 4 bytes
    pub b_frame_index: u8,
    pub bm_capabilities: u8,
    // _padding: u8, // No explicit padding needed if we use u32 for subtype, but alignment might add it
    pub w_width: u16,
    pub w_height: u16,
    pub dw_min_bit_rate: u32,
    pub dw_max_bit_rate: u32,
    pub dw_max_video_frame_buffer_size: u32,
    pub dw_default_frame_interval: u32,
    pub dw_min_frame_interval: u32,
    pub dw_max_frame_interval: u32,
    pub dw_frame_interval_step: u32,
    pub b_frame_interval_type: u8,
    // _padding2: [u8; 3],
    pub dw_bytes_per_line: u32,
    pub intervals: *mut u32,
}

// ============================================================================
// Device descriptor.
// ============================================================================

#[repr(C)]
pub struct UvcDeviceDescriptor {
    pub vendor_id: u16,
    pub product_id: u16,
    pub bcd_uvc: u16,
    pub serial_number: *const c_char,
    pub manufacturer: *const c_char,
    pub product: *const c_char,
}

// ============================================================================
// Frame structure. This must exactly match struct uvc_frame in
// libuvc/include/libuvc/libuvc.h. On macOS ARM64:
//   - size_t = 8 bytes
//   - uint32_t = 4 bytes
//   - timeval = 16 bytes (tv_sec: i64, tv_usec: i32 + 4 padding)
//   - timespec = 16 bytes (tv_sec: i64, tv_nsec: i64)
//   - pointer = 8 bytes
// ============================================================================

#[repr(C)]
pub struct UvcFrame {
    /// Image data for this frame
    pub data: *mut c_void, // offset 0, 8 bytes
    /// Size of image data buffer
    pub data_bytes: size_t, // offset 8, 8 bytes
    /// Width of image in pixels
    pub width: u32, // offset 16, 4 bytes
    /// Height of image in pixels
    pub height: u32, // offset 20, 4 bytes
    /// Pixel data format
    pub frame_format: UvcFrameFormat, // offset 24, 4 bytes (enum)
    /// Padding for alignment
    _pad1: u32, // offset 28, 4 bytes padding
    /// Number of bytes per horizontal line (undefined for compressed format)
    pub step: size_t, // offset 32, 8 bytes
    /// Frame number (may skip, but is strictly monotonically increasing)
    pub sequence: u32, // offset 40, 4 bytes
    /// Padding for alignment before timeval
    _pad2: u32, // offset 44, 4 bytes padding
    /// Estimate of system time when the device started capturing the image
    pub capture_time: timeval, // offset 48, 16 bytes
    /// Estimate of system time when the device finished receiving the image
    pub capture_time_finished: timespec, // offset 64, 16 bytes
    /// Handle on the device that produced the image
    pub source: *mut UvcDeviceHandle, // offset 80, 8 bytes
    /// Is the data buffer owned by the library?
    pub library_owns_data: u8, // offset 88, 1 byte
    /// Padding for alignment
    _pad3: [u8; 7], // offset 89, 7 bytes padding
    /// Metadata for this frame if available
    pub metadata: *mut c_void, // offset 96, 8 bytes
    /// Metadata size in bytes
    pub metadata_bytes: size_t, // offset 104, 8 bytes
                                // Total size: 112 bytes
}

// ============================================================================
// Stream control structure.
// ============================================================================

#[repr(C)]
#[derive(Clone, Copy)]
pub struct UvcStreamCtrlParams {
    pub bm_hint: u16,
    pub b_format_index: u8,
    pub b_frame_index: u8,
    pub dw_frame_interval: u32,
    pub w_key_frame_rate: u16,
    pub w_p_frame_rate: u16,
    pub w_comp_quality: u16,
    pub w_comp_window_size: u16,
    pub w_delay: u16,
    pub dw_max_video_frame_size: u32,
    pub dw_max_payload_transfer_size: u32,
}

// ============================================================================
// Callback types.
// ============================================================================

pub type UvcFrameCallback = extern "C" fn(frame: *mut UvcFrame, user_ptr: *mut c_void);

pub type UvcStatusCallback = extern "C" fn(
    status_class: c_int,
    event: c_int,
    selector: c_int,
    status_attribute: c_int,
    data: *mut c_void,
    data_len: size_t,
    user_ptr: *mut c_void,
);

pub type UvcButtonCallback = extern "C" fn(button: c_int, state: c_int, user_ptr: *mut c_void);

// ============================================================================
// libusb options used for Android support.
// ============================================================================

/// libusb option values.
#[repr(C)]
pub enum LibusbOption {
    /// Uses the UsbDk backend on Windows.
    UseUsbdk = 1,
    /// Disables device discovery as required by the Android FD path.
    NoDeviceDiscovery = 2,
}

// ============================================================================
// FFI function declarations.
// ============================================================================

extern "C" {
    // libusb option setup for Android.
    /// Sets a libusb option.
    /// A null context changes the global default.
    pub fn libusb_set_option(ctx: *mut LibusbContext, option: LibusbOption, ...) -> c_int;

    // Context management.
    pub fn uvc_init(ctx: *mut *mut UvcContext, usb_ctx: *mut LibusbContext) -> UvcError;
    pub fn uvc_init2(ctx: *mut *mut UvcContext, usb_ctx: *mut LibusbContext) -> UvcError;
    pub fn uvc_exit(ctx: *mut UvcContext);

    // Device discovery.
    pub fn uvc_find_device(
        ctx: *mut UvcContext,
        dev: *mut *mut UvcDevice,
        vid: c_int,
        pid: c_int,
        sn: *const c_char,
    ) -> UvcError;

    pub fn uvc_get_device_list(ctx: *mut UvcContext, list: *mut *mut *mut UvcDevice) -> UvcError;

    pub fn uvc_free_device_list(list: *mut *mut UvcDevice, unref_devices: u8);

    // Device descriptors.
    pub fn uvc_get_device_descriptor(
        dev: *mut UvcDevice,
        desc: *mut *mut UvcDeviceDescriptor,
    ) -> UvcError;

    pub fn uvc_free_device_descriptor(desc: *mut UvcDeviceDescriptor);

    // Device references.
    pub fn uvc_ref_device(dev: *mut UvcDevice);
    pub fn uvc_unref_device(dev: *mut UvcDevice);

    // Device open and close.
    pub fn uvc_open(dev: *mut UvcDevice, devh: *mut *mut UvcDeviceHandle) -> UvcError;
    pub fn uvc_close(devh: *mut UvcDeviceHandle);

    // Android file descriptor support.
    pub fn uvc_wrap(fd: c_int, ctx: *mut UvcContext, devh: *mut *mut UvcDeviceHandle) -> UvcError;

    // Stream control.
    pub fn uvc_get_stream_ctrl_format_size(
        devh: *mut UvcDeviceHandle,
        ctrl: *mut UvcStreamCtrl,
        format: UvcFrameFormat,
        width: c_int,
        height: c_int,
        fps: c_int,
    ) -> UvcError;

    pub fn uvc_probe_stream_ctrl(devh: *mut UvcDeviceHandle, ctrl: *mut UvcStreamCtrl) -> c_int;
    pub fn uvc_start_streaming(
        devh: *mut UvcDeviceHandle,
        ctrl: *mut UvcStreamCtrl,
        cb: UvcFrameCallback,
        user_ptr: *mut c_void,
        flags: u8,
    ) -> UvcError;

    pub fn uvc_stop_streaming(devh: *mut UvcDeviceHandle);

    // Format enumeration.
    pub fn uvc_get_format_descs(devh: *mut UvcDeviceHandle) -> *const UvcFormatDesc;

    // Frame management.
    pub fn uvc_allocate_frame(data_bytes: size_t) -> *mut UvcFrame;
    pub fn uvc_free_frame(frame: *mut UvcFrame);

    // MJPEG decoding now uses the Rust turbojpeg crate, so the C conversion
    // functions such as uvc_mjpeg2rgb and uvc_yuyv2rgb are not required.

    // ==================== Camera controls ====================

    // Automatic exposure mode.
    pub fn uvc_get_ae_mode(devh: *mut UvcDeviceHandle, mode: *mut u8, req_code: u8) -> UvcError;

    pub fn uvc_set_ae_mode(devh: *mut UvcDeviceHandle, mode: u8) -> UvcError;

    // Absolute exposure time.
    pub fn uvc_get_exposure_abs(
        devh: *mut UvcDeviceHandle,
        time: *mut u32,
        req_code: u8,
    ) -> UvcError;

    pub fn uvc_set_exposure_abs(devh: *mut UvcDeviceHandle, time: u32) -> UvcError;

    // Absolute focus.
    pub fn uvc_get_focus_abs(devh: *mut UvcDeviceHandle, focus: *mut u16, req_code: u8)
        -> UvcError;

    pub fn uvc_set_focus_abs(devh: *mut UvcDeviceHandle, focus: u16) -> UvcError;

    // Automatic focus.
    pub fn uvc_get_focus_auto(devh: *mut UvcDeviceHandle, state: *mut u8, req_code: u8)
        -> UvcError;

    pub fn uvc_set_focus_auto(devh: *mut UvcDeviceHandle, state: u8) -> UvcError;

    // Absolute zoom.
    pub fn uvc_get_zoom_abs(
        devh: *mut UvcDeviceHandle,
        focal_length: *mut u16,
        req_code: u8,
    ) -> UvcError;

    pub fn uvc_set_zoom_abs(devh: *mut UvcDeviceHandle, focal_length: u16) -> UvcError;

    // Brightness.
    pub fn uvc_get_brightness(
        devh: *mut UvcDeviceHandle,
        brightness: *mut i16,
        req_code: u8,
    ) -> UvcError;

    pub fn uvc_set_brightness(devh: *mut UvcDeviceHandle, brightness: i16) -> UvcError;

    // Contrast.
    pub fn uvc_get_contrast(
        devh: *mut UvcDeviceHandle,
        contrast: *mut u16,
        req_code: u8,
    ) -> UvcError;

    pub fn uvc_set_contrast(devh: *mut UvcDeviceHandle, contrast: u16) -> UvcError;

    // Saturation.
    pub fn uvc_get_saturation(
        devh: *mut UvcDeviceHandle,
        saturation: *mut u16,
        req_code: u8,
    ) -> UvcError;

    pub fn uvc_set_saturation(devh: *mut UvcDeviceHandle, saturation: u16) -> UvcError;

    // Hue.
    pub fn uvc_get_hue(devh: *mut UvcDeviceHandle, hue: *mut i16, req_code: u8) -> UvcError;

    pub fn uvc_set_hue(devh: *mut UvcDeviceHandle, hue: i16) -> UvcError;

    // Sharpness.
    pub fn uvc_get_sharpness(
        devh: *mut UvcDeviceHandle,
        sharpness: *mut u16,
        req_code: u8,
    ) -> UvcError;

    pub fn uvc_set_sharpness(devh: *mut UvcDeviceHandle, sharpness: u16) -> UvcError;

    // Gamma.
    pub fn uvc_get_gamma(devh: *mut UvcDeviceHandle, gamma: *mut u16, req_code: u8) -> UvcError;

    pub fn uvc_set_gamma(devh: *mut UvcDeviceHandle, gamma: u16) -> UvcError;

    // White balance temperature.
    pub fn uvc_get_white_balance_temperature(
        devh: *mut UvcDeviceHandle,
        temperature: *mut u16,
        req_code: u8,
    ) -> UvcError;

    pub fn uvc_set_white_balance_temperature(
        devh: *mut UvcDeviceHandle,
        temperature: u16,
    ) -> UvcError;

    // Automatic white balance.
    pub fn uvc_get_white_balance_temperature_auto(
        devh: *mut UvcDeviceHandle,
        state: *mut u8,
        req_code: u8,
    ) -> UvcError;

    pub fn uvc_set_white_balance_temperature_auto(
        devh: *mut UvcDeviceHandle,
        state: u8,
    ) -> UvcError;

    // Gain.
    pub fn uvc_get_gain(devh: *mut UvcDeviceHandle, gain: *mut u16, req_code: u8) -> UvcError;

    pub fn uvc_set_gain(devh: *mut UvcDeviceHandle, gain: u16) -> UvcError;

    // Backlight compensation.
    pub fn uvc_get_backlight_compensation(
        devh: *mut UvcDeviceHandle,
        backlight_compensation: *mut u16,
        req_code: u8,
    ) -> UvcError;

    pub fn uvc_set_backlight_compensation(
        devh: *mut UvcDeviceHandle,
        backlight_compensation: u16,
    ) -> UvcError;

    // Additional utility functions.
    pub fn uvc_perror(err: UvcError, msg: *const c_char);
    pub fn uvc_strerror(err: UvcError) -> *const c_char;
}

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

    #[test]
    fn test_error_codes() {
        assert_eq!(UVC_SUCCESS, 0);
        assert_eq!(UVC_ERROR_IO, -1);
    }

    #[test]
    fn test_frame_format() {
        assert_eq!(UvcFrameFormat::Mjpeg as i32, 7);
        assert_eq!(UvcFrameFormat::Yuyv as i32, 3);
    }
}

// Check the layout on every target, including cross-compiled Android ARMv7.
const _: () = {
    assert!(
        std::mem::size_of::<UvcFrameDesc>()
            == if cfg!(target_pointer_width = "64") {
                80
            } else {
                64
            }
    );
    assert!(
        std::mem::offset_of!(UvcFrameDesc, w_width)
            == if cfg!(target_pointer_width = "64") {
                30
            } else {
                18
            }
    );
    assert!(
        std::mem::offset_of!(UvcFrameDesc, dw_default_frame_interval)
            == if cfg!(target_pointer_width = "64") {
                48
            } else {
                36
            }
    );
};
#[cfg(test)]
mod abi_tests {
    use super::*;
    use std::mem::{offset_of, size_of};
    extern "C" {
        fn camera_uvc_abi_value(index: u32) -> usize;
    }
    #[test]
    fn rust_layout_matches_the_compiled_c_headers() {
        let rust = [
            size_of::<UvcFrameDesc>(),
            offset_of!(UvcFrameDesc, w_width),
            offset_of!(UvcFrameDesc, w_height),
            offset_of!(UvcFrameDesc, dw_default_frame_interval),
            offset_of!(UvcFrameDesc, intervals),
            size_of::<UvcFormatDesc>(),
            offset_of!(UvcFormatDesc, guid_format),
            offset_of!(UvcFormatDesc, frame_descs),
            size_of::<UvcFrame>(),
            offset_of!(UvcFrame, data),
            offset_of!(UvcFrame, data_bytes),
            offset_of!(UvcFrame, step),
            offset_of!(UvcFrame, sequence),
        ];
        for (index, value) in rust.into_iter().enumerate() {
            assert_eq!(
                value,
                unsafe { camera_uvc_abi_value(index as u32) },
                "ABI field {index}"
            );
        }
    }
}