apple-vision 0.15.1

Safe Rust bindings for Apple's Vision framework — OCR, object detection, face landmarks on macOS
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
//! Explicit request / handler / video-processing wrappers backed by Vision.
//!
//! This module exposes the generic Vision base classes that the rest of the
//! crate used internally until v0.15.1: [`Request`] (`VNRequest`),
//! [`Observation`] (`VNObservation`), [`ImageRequestHandler`]
//! (`VNImageRequestHandler`), [`SequenceRequestHandler`]
//! (`VNSequenceRequestHandler`), and [`VideoProcessor`] (`VNVideoProcessor`).
//! The initial safe surface focuses on text recognition, which is already part
//! of the crate's default feature set.

use core::{
    ffi::{c_char, c_void},
    ptr,
};
use std::{
    ffi::{CStr, CString},
    path::{Path, PathBuf},
};

use crate::{
    error::{from_swift, VisionError},
    ffi,
    recognize_text::{BoundingBox, RecognitionLevel, RecognizedText},
};

const VIDEO_CADENCE_DEFAULT: i32 = 0;
const VIDEO_CADENCE_FRAME_RATE: i32 = 1;
const VIDEO_CADENCE_TIME_INTERVAL: i32 = 2;

/// The high-level Vision request kind carried by [`Request`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RequestKind {
    /// `VNRecognizeTextRequest`
    RecognizeText,
}

/// Shared `VNRequest` configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
    kind: RequestKind,
    recognition_level: RecognitionLevel,
    uses_language_correction: bool,
    prefer_background_processing: bool,
    uses_cpu_only: bool,
    revision: Option<usize>,
}

impl Default for Request {
    fn default() -> Self {
        Self::recognize_text()
    }
}

impl Request {
    /// Build a text-recognition request backed by `VNRecognizeTextRequest`.
    #[must_use]
    pub const fn recognize_text() -> Self {
        Self {
            kind: RequestKind::RecognizeText,
            recognition_level: RecognitionLevel::Accurate,
            uses_language_correction: true,
            prefer_background_processing: false,
            uses_cpu_only: false,
            revision: None,
        }
    }

    /// Return the underlying request kind.
    #[must_use]
    pub const fn kind(&self) -> RequestKind {
        self.kind
    }

    /// Select the OCR recognition strategy.
    #[must_use]
    pub const fn with_recognition_level(mut self, recognition_level: RecognitionLevel) -> Self {
        self.recognition_level = recognition_level;
        self
    }

    /// Enable or disable language correction.
    #[must_use]
    pub const fn with_language_correction(mut self, enabled: bool) -> Self {
        self.uses_language_correction = enabled;
        self
    }

    /// Mirror `VNRequest.preferBackgroundProcessing`.
    #[must_use]
    pub const fn with_prefer_background_processing(mut self, enabled: bool) -> Self {
        self.prefer_background_processing = enabled;
        self
    }

    /// Mirror `VNRequest.usesCPUOnly`.
    #[must_use]
    pub const fn with_uses_cpu_only(mut self, enabled: bool) -> Self {
        self.uses_cpu_only = enabled;
        self
    }

    /// Override the request revision.
    #[must_use]
    pub const fn with_revision(mut self, revision: usize) -> Self {
        self.revision = Some(revision);
        self
    }

    #[must_use]
    pub const fn recognition_level(&self) -> RecognitionLevel {
        self.recognition_level
    }

    #[must_use]
    pub const fn uses_language_correction(&self) -> bool {
        self.uses_language_correction
    }

    #[must_use]
    pub const fn prefer_background_processing(&self) -> bool {
        self.prefer_background_processing
    }

    #[must_use]
    pub const fn uses_cpu_only(&self) -> bool {
        self.uses_cpu_only
    }

    #[must_use]
    pub const fn revision(&self) -> Option<usize> {
        self.revision
    }

    const fn recognition_level_raw(&self) -> i32 {
        match self.recognition_level {
            RecognitionLevel::Fast => 0,
            RecognitionLevel::Accurate => 1,
        }
    }
}

/// Shared `VNObservation` metadata surfaced by Vision results.
#[derive(Debug, Clone, PartialEq)]
pub struct Observation {
    /// Stable UUID generated by Vision for this observation.
    pub uuid: String,
    /// Base confidence score in `0.0..=1.0`.
    pub confidence: f32,
    /// Optional media time range in seconds.
    pub time_range: Option<TimeRange>,
}

/// Media time range in seconds.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TimeRange {
    pub start_seconds: f64,
    pub duration_seconds: f64,
}

/// One recognized-text observation plus shared [`Observation`] metadata.
#[derive(Debug, Clone, PartialEq)]
pub struct RecognizedTextObservation {
    pub observation: Observation,
    pub text: String,
    pub bounding_box: BoundingBox,
}

impl RecognizedTextObservation {
    /// Drop the generic observation metadata and keep the existing text result
    /// shape used elsewhere in the crate.
    #[must_use]
    pub fn into_recognized_text(self) -> RecognizedText {
        self.into()
    }

    /// Clone into the existing [`RecognizedText`] shape.
    #[must_use]
    pub fn as_recognized_text(&self) -> RecognizedText {
        self.clone().into()
    }
}

impl From<RecognizedTextObservation> for RecognizedText {
    fn from(value: RecognizedTextObservation) -> Self {
        Self {
            text: value.text,
            confidence: value.observation.confidence,
            bounding_box: value.bounding_box,
        }
    }
}

/// Safe wrapper around `VNImageRequestHandler`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageRequestHandler {
    image_path: PathBuf,
}

impl ImageRequestHandler {
    /// Bind the handler to an image path.
    #[must_use]
    pub fn new(image_path: impl AsRef<Path>) -> Self {
        Self {
            image_path: image_path.as_ref().to_path_buf(),
        }
    }

    /// Perform `request` against the bound image.
    ///
    /// # Errors
    ///
    /// Returns [`VisionError`] if the path is invalid, the image cannot be
    /// loaded, or Vision rejects the request.
    pub fn perform(&self, request: &Request) -> Result<Vec<RecognizedTextObservation>, VisionError> {
        let image_c = path_to_cstring(&self.image_path, "image path")?;
        let mut out_array: *mut c_void = ptr::null_mut();
        let mut out_count: usize = 0;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::vn_image_request_handler_perform_text_request(
                image_c.as_ptr(),
                request.recognition_level_raw(),
                request.uses_language_correction,
                request.prefer_background_processing,
                request.uses_cpu_only,
                request.revision.unwrap_or_default(),
                request.revision.is_some(),
                &mut out_array,
                &mut out_count,
                &mut err_msg,
            )
        };
        if status != ffi::status::OK {
            return Err(unsafe { from_swift(status, err_msg) });
        }
        Ok(collect_request_observations(out_array, out_count))
    }
}

/// Safe wrapper around a retained `VNSequenceRequestHandler`.
pub struct SequenceRequestHandler {
    handle: *mut c_void,
}

impl SequenceRequestHandler {
    /// Create a fresh sequence handler.
    ///
    /// # Errors
    ///
    /// Returns [`VisionError`] if the Swift bridge fails to allocate the
    /// backing handler.
    pub fn new() -> Result<Self, VisionError> {
        let mut handle: *mut c_void = ptr::null_mut();
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe { ffi::vn_sequence_request_handler_create(&mut handle, &mut err_msg) };
        if status != ffi::status::OK {
            return Err(unsafe { from_swift(status, err_msg) });
        }
        if handle.is_null() {
            return Err(VisionError::Unknown {
                code: ffi::status::UNKNOWN,
                message: "sequence request handler bridge returned a null handle".into(),
            });
        }
        Ok(Self { handle })
    }

    /// Perform `request` on `image_path`, preserving Vision's sequence state
    /// across calls.
    ///
    /// # Errors
    ///
    /// Returns [`VisionError`] if the path is invalid, the image cannot be
    /// loaded, or Vision rejects the request.
    pub fn perform(
        &mut self,
        image_path: impl AsRef<Path>,
        request: &Request,
    ) -> Result<Vec<RecognizedTextObservation>, VisionError> {
        let image_c = path_to_cstring(image_path.as_ref(), "image path")?;
        let mut out_array: *mut c_void = ptr::null_mut();
        let mut out_count: usize = 0;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::vn_sequence_request_handler_perform_text_request(
                self.handle,
                image_c.as_ptr(),
                request.recognition_level_raw(),
                request.uses_language_correction,
                request.prefer_background_processing,
                request.uses_cpu_only,
                request.revision.unwrap_or_default(),
                request.revision.is_some(),
                &mut out_array,
                &mut out_count,
                &mut err_msg,
            )
        };
        if status != ffi::status::OK {
            return Err(unsafe { from_swift(status, err_msg) });
        }
        Ok(collect_request_observations(out_array, out_count))
    }
}

impl Drop for SequenceRequestHandler {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            unsafe { ffi::vn_sequence_request_handler_free(self.handle) };
        }
    }
}

/// Cadence override for [`VideoProcessor`].
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum VideoCadence {
    /// Let Vision process every frame.
    EveryFrame,
    /// Sample the video at the given frame rate.
    FrameRate(usize),
    /// Sample the video at the given time interval, in seconds.
    TimeIntervalSeconds(f64),
}

/// `VNVideoProcessor` request options.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct VideoProcessingOptions {
    pub cadence: Option<VideoCadence>,
}

impl Default for VideoProcessingOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl VideoProcessingOptions {
    #[must_use]
    pub const fn new() -> Self {
        Self { cadence: None }
    }

    #[must_use]
    pub const fn with_cadence(mut self, cadence: VideoCadence) -> Self {
        self.cadence = Some(cadence);
        self
    }
}

/// Safe wrapper around `VNVideoProcessor`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VideoProcessor {
    video_path: PathBuf,
}

impl VideoProcessor {
    /// Bind the processor to a video file.
    #[must_use]
    pub fn new(video_path: impl AsRef<Path>) -> Self {
        Self {
            video_path: video_path.as_ref().to_path_buf(),
        }
    }

    /// Analyze the bound video with `request`.
    ///
    /// # Errors
    ///
    /// Returns [`VisionError`] if the path is invalid, the video cannot be
    /// opened, the cadence is invalid, or Vision rejects the request.
    pub fn analyze(
        &self,
        request: &Request,
        options: VideoProcessingOptions,
    ) -> Result<Vec<RecognizedTextObservation>, VisionError> {
        let video_c = path_to_cstring(&self.video_path, "video path")?;
        let (cadence_kind, cadence_value) = cadence_to_ffi(options.cadence)?;
        let mut out_array: *mut c_void = ptr::null_mut();
        let mut out_count: usize = 0;
        let mut err_msg: *mut c_char = ptr::null_mut();
        let status = unsafe {
            ffi::vn_video_processor_analyze_text_request(
                video_c.as_ptr(),
                request.recognition_level_raw(),
                request.uses_language_correction,
                request.prefer_background_processing,
                request.uses_cpu_only,
                request.revision.unwrap_or_default(),
                request.revision.is_some(),
                cadence_kind,
                cadence_value,
                &mut out_array,
                &mut out_count,
                &mut err_msg,
            )
        };
        if status != ffi::status::OK {
            return Err(unsafe { from_swift(status, err_msg) });
        }
        Ok(collect_request_observations(out_array, out_count))
    }
}

fn cadence_to_ffi(cadence: Option<VideoCadence>) -> Result<(i32, f64), VisionError> {
    match cadence.unwrap_or(VideoCadence::EveryFrame) {
        VideoCadence::EveryFrame => Ok((VIDEO_CADENCE_DEFAULT, 0.0)),
        VideoCadence::FrameRate(frame_rate) => {
            if frame_rate == 0 {
                return Err(VisionError::InvalidArgument(
                    "video cadence frame rate must be greater than zero".into(),
                ));
            }
            let frame_rate = u32::try_from(frame_rate).map_err(|_| {
                VisionError::InvalidArgument(
                    "video cadence frame rate exceeds the supported range".into(),
                )
            })?;
            Ok((VIDEO_CADENCE_FRAME_RATE, f64::from(frame_rate)))
        }
        VideoCadence::TimeIntervalSeconds(seconds) => {
            if !seconds.is_finite() || seconds <= 0.0 {
                return Err(VisionError::InvalidArgument(
                    "video cadence time interval must be a finite positive number".into(),
                ));
            }
            Ok((VIDEO_CADENCE_TIME_INTERVAL, seconds))
        }
    }
}

fn collect_request_observations(
    array: *mut c_void,
    count: usize,
) -> Vec<RecognizedTextObservation> {
    if array.is_null() || count == 0 {
        return Vec::new();
    }

    let typed = array.cast::<ffi::RequestObservationRaw>();
    let mut observations = Vec::with_capacity(count);
    for index in 0..count {
        let raw = unsafe { &*typed.add(index) };
        let uuid = c_string_or_empty(raw.uuid);
        let text = c_string_or_empty(raw.text);
        let time_range = raw.has_time_range.then_some(TimeRange {
            start_seconds: raw.time_range_start_seconds,
            duration_seconds: raw.time_range_duration_seconds,
        });
        observations.push(RecognizedTextObservation {
            observation: Observation {
                uuid,
                confidence: raw.confidence,
                time_range,
            },
            text,
            bounding_box: BoundingBox {
                x: raw.bbox_x,
                y: raw.bbox_y,
                width: raw.bbox_w,
                height: raw.bbox_h,
            },
        });
    }

    unsafe { ffi::vn_request_observations_free(array, count) };
    observations
}

fn c_string_or_empty(ptr: *mut c_char) -> String {
    if ptr.is_null() {
        String::new()
    } else {
        unsafe { CStr::from_ptr(ptr) }.to_string_lossy().into_owned()
    }
}

fn path_to_cstring(path: &Path, label: &str) -> Result<CString, VisionError> {
    let path_str = path
        .to_str()
        .ok_or_else(|| VisionError::InvalidArgument(format!("non-UTF-8 {label}")))?;
    CString::new(path_str)
        .map_err(|err| VisionError::InvalidArgument(format!("{label} NUL byte: {err}")))
}

#[doc(hidden)]
/// Test helper used by the smoke test + example — renders a tiny MOV file with
/// two text segments so `VNVideoProcessor` can be exercised without fixture
/// assets checked into git.
pub fn _test_helper_render_text_video(
    first_text: &str,
    second_text: &str,
    width: i32,
    height: i32,
    fps: i32,
    frames_per_text: i32,
    path: &Path,
) -> Result<(), VisionError> {
    let first_c =
        CString::new(first_text).map_err(|err| VisionError::InvalidArgument(err.to_string()))?;
    let second_c =
        CString::new(second_text).map_err(|err| VisionError::InvalidArgument(err.to_string()))?;
    let path_c = CString::new(path.to_string_lossy().as_ref())
        .map_err(|err| VisionError::InvalidArgument(err.to_string()))?;
    let status = unsafe {
        ffi::vn_test_helper_render_text_video(
            first_c.as_ptr(),
            second_c.as_ptr(),
            width,
            height,
            fps,
            frames_per_text,
            path_c.as_ptr(),
        )
    };
    if status != ffi::status::OK {
        return Err(VisionError::Unknown {
            code: status,
            message: "video render helper failed".into(),
        });
    }
    Ok(())
}