hik_mvs_sdk/lib.rs
1//! Safe Rust API for Hikrobot MVS cameras.
2//! Hikrobot MVS 相机的安全 Rust API。
3//!
4//! The crate keeps Hikrobot's C/C++ types behind a small C ABI. Camera handles and frame
5//! 本 crate 通过精简的 C ABI 隔离 Hikrobot 的 C/C++ 类型。相机句柄与帧
6//! buffers are released through RAII, while callback data is copied into Rust-owned memory
7//! 缓冲区通过 RAII 释放,回调数据则复制到 Rust 自有内存中,
8//! before it leaves the SDK callback thread.
9//! 确保数据离开 SDK 回调线程前已经完成复制。
10//!
11//! # Typical workflow
12//! # 典型工作流程
13//!
14//! 1. Create one [`Sdk`] guard with [`Sdk::initialize`].
15//! 1. 使用 `Sdk::initialize` 创建一个 `Sdk` 生命周期守卫。
16//! 2. Discover devices with [`Sdk::enumerate`] and open one by serial number.
17//! 2. 使用 `Sdk::enumerate` 发现设备,并按序列号打开相机。
18//! 3. Configure GenICam nodes, select a trigger mode, then call [`Camera::start`].
19//! 3. 配置 GenICam 节点并选择触发模式,然后调用 `Camera::start`。
20//! 4. Acquire frames with [`Camera::grab`] or [`Camera::frame_channel`].
21//! 4. 使用 `Camera::grab` 或 `Camera::frame_channel` 获取帧。
22//!
23//! Dropping [`Frame`], [`Camera`], and [`Sdk`] releases resources in the required order.
24//! `Frame`、`Camera` 和 `Sdk` 析构时会按要求的顺序释放资源。
25#![warn(missing_docs)]
26
27mod sys;
28
29/// Camera handles, acquisition control, and general operations.
30/// 相机句柄、采集控制与通用操作。
31pub mod camera;
32/// Error and result types.
33/// 错误和结果类型。
34pub mod error;
35/// Callbacks, asynchronous events, and network statistics.
36/// 回调、异步事件和网络统计。
37pub mod events;
38/// Frame buffers, Chunk metadata, and output formats.
39/// 帧缓冲、Chunk 元数据与输出格式。
40pub mod frame;
41/// Image encoding and geometric transformation types.
42/// 图片编码和几何变换类型。
43pub mod imaging;
44/// GenICam parameter values and constraints.
45/// GenICam 参数值及约束类型。
46pub mod params;
47/// SDK lifetime, discovery, and network-level operations.
48/// SDK 生命周期、设备发现与网络级操作。
49pub mod sdk;
50
51use std::{
52 ffi::{CStr, CString},
53 marker::PhantomData,
54 ptr::NonNull,
55 slice,
56 sync::mpsc,
57};
58
59/// Result type returned by all fallible high-level operations in this crate.
60/// 该箱中所有可出错的高层操作返回的结果类型。
61pub type Result<T> = std::result::Result<T, Error>;
62
63/// Error produced by the safe wrapper before or during an MVS operation.
64/// 安全封装层在MVS操作前或运行期间产生的错误。
65#[derive(Debug, thiserror::Error)]
66pub enum Error {
67 /// An error code returned by the wrapper or the MVS SDK.
68 /// 封装器或MVS SDK返回的错误代码。
69 #[error("{message} (MVS/wrapper code 0x{code:08X})", code = *code as u32)]
70 Sdk {
71 /// Raw signed wrapper or MVS status code.
72 /// 封装层或 MVS 返回的原始有符号状态码。
73 code: i32,
74 /// Operation-specific diagnostic copied from the native thread-local error buffer.
75 /// 操作特定诊断从原生线程局部错误缓冲区复制。
76 message: String,
77 },
78 /// A Rust string could not be passed through the C ABI because it contains `\0`.
79 /// Rust字符串无法通过C ABI,因为它包含“\0”。
80 #[error("{field} contains an interior NUL byte")]
81 InteriorNul {
82 /// Logical argument name containing the invalid byte.
83 /// 逻辑参数名称包含无效字节。
84 field: &'static str,
85 },
86}
87
88fn check(code: i32) -> Result<()> {
89 if code == sys::HIK_OK {
90 return Ok(());
91 }
92 // SAFETY: the wrapper returns a thread-local NUL-terminated string whose storage remains
93 // 安全:包装器返回一个线程本地的 NUL 终止字符串,其存储仍保留
94 // valid until the next wrapper error on this thread. We copy it before returning.
95 // 有效,直到本线程下一次封装错误。我们会在返回前复制它。
96 let message = unsafe {
97 let ptr = sys::hik_last_error();
98 if ptr.is_null() {
99 "unknown error".into()
100 } else {
101 CStr::from_ptr(ptr).to_string_lossy().into_owned()
102 }
103 };
104 Err(Error::Sdk { code, message })
105}
106
107fn cstring(value: &str, field: &'static str) -> Result<CString> {
108 CString::new(value).map_err(|_| Error::InteriorNul { field })
109}
110
111fn text(chars: &[std::ffi::c_char]) -> String {
112 // SAFETY: every fixed-size native string passed here is zero-initialized by the wrapper and
113 // 安全性:这里传递的每个固定大小的本地字符串都被包装器初始化为零,且
114 // explicitly NUL-terminated before crossing the ABI.
115 // 明确在跨越 ABI之前被NUL 结尾。
116 unsafe {
117 CStr::from_ptr(chars.as_ptr())
118 .to_string_lossy()
119 .into_owned()
120 }
121}
122
123/// Owned camera description produced by device enumeration.
124/// 自有相机描述由设备枚举生成。
125#[derive(Debug, Clone)]
126pub struct DeviceInfo {
127 /// Physical transport used by the device.
128 /// 设备使用的物理传输方式。
129 pub transport: Transport,
130 /// Current IPv4 address for GigE cameras; `None` for transports without an IP address.
131 /// GigE相机当前IPv4地址;没有IP地址的传输则显示“无”。
132 pub ip: Option<std::net::Ipv4Addr>,
133 /// Manufacturer model name, for example `MV-CS016-10GC`.
134 /// 制造商型号名称,例如“MV-CS016-10GC”。
135 pub model: String,
136 /// Stable manufacturer serial number used by [`Sdk::open`].
137 /// 稳定的制造商序列号由Sdk::open使用。
138 pub serial: String,
139 /// User-defined device name stored in the camera.
140 /// 存储在相机中的用户自定义设备名称。
141 pub user_name: String,
142}
143
144/// Camera transport reported by the MVS enumeration API.
145/// MVS枚举API报告的相机传输。
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum Transport {
148 /// GigE Vision camera.
149 /// GigE Vision相机。
150 GigE,
151 /// USB3 Vision camera.
152 /// USB3 Vision 相机。
153 Usb3,
154 /// Transport not yet represented by this crate.
155 /// 该 crate 尚未表示此传输类型。
156 Unknown,
157}
158
159/// Process-level MVS SDK lifetime guard.
160/// 进程级MVS SDK生命周期守护。
161///
162/// Keep this value alive for at least as long as every [`Camera`] opened from it. The borrow
163/// 此值必须至少与从中打开的每个 `Camera` 存活同样长;
164/// carried by `Camera<'sdk>` enforces that ordering for safe Rust code.
165/// `Camera<'sdk>` 携带的借用关系会在安全 Rust 代码中强制保证此析构顺序。
166pub struct Sdk;
167
168impl Sdk {
169 /// Initializes the process-wide MVS runtime.
170 /// 初始化进程范围的MVS运行时。
171 ///
172 /// # Errors
173 /// # 错误
174 /// Returns [`Error::Sdk`] when `MV_CC_Initialize` fails.
175 /// 当“MV_CC_Initialize”失败时返回错误::sdk。
176 pub fn initialize() -> Result<Self> {
177 check(unsafe { sys::hik_initialize() })?;
178 Ok(Self)
179 }
180
181 /// Returns the version of the currently loaded MVS runtime.
182 /// 返回当前加载的MVS运行时版本。
183 pub fn version(&self) -> SdkVersion {
184 SdkVersion::from_raw(unsafe { sys::hik_sdk_version() })
185 }
186
187 /// Enumerates GigE Vision and USB3 Vision cameras and returns owned descriptions.
188 /// 列举GigE Vision和USB3 Vision相机,并返回自有描述。
189 ///
190 /// # Errors
191 /// # 错误
192 /// Returns an SDK error when device discovery fails.
193 /// 设备发现失败时会返回SDK错误。
194 pub fn enumerate(&self) -> Result<Vec<DeviceInfo>> {
195 let mut count = 0;
196 check(unsafe { sys::hik_enumerate(std::ptr::null_mut(), 0, &mut count) })?;
197 let blank = sys::HikDeviceInfo {
198 transport: 0,
199 ip: 0,
200 model: [0; 64],
201 serial: [0; 64],
202 user_name: [0; 64],
203 };
204 let mut raw = vec![blank; count];
205 check(unsafe { sys::hik_enumerate(raw.as_mut_ptr(), raw.len(), &mut count) })?;
206 raw.truncate(count.min(raw.len()));
207 Ok(raw
208 .into_iter()
209 .map(|d| DeviceInfo {
210 transport: match d.transport {
211 1 => Transport::GigE,
212 2 => Transport::Usb3,
213 _ => Transport::Unknown,
214 },
215 ip: (d.ip != 0).then(|| std::net::Ipv4Addr::from(d.ip)),
216 model: text(&d.model),
217 serial: text(&d.serial),
218 user_name: text(&d.user_name),
219 })
220 .collect())
221 }
222
223 /// Opens a camera by stable manufacturer serial number using exclusive access.
224 /// 通过独占访问,按稳定厂商序列号打开相机。
225 ///
226 /// The returned camera cannot outlive this SDK guard. GigE packet size optimization is
227 /// 退回的相机无法比这个SDK守卫活得久。GigE数据包大小优化为
228 /// applied automatically when the driver can determine an optimal value.
229 /// 当驱动程序能够确定最优值时,会自动应用。
230 ///
231 /// # Errors
232 /// # 错误
233 /// Returns an error for an unknown serial, an inaccessible device, or invalid input text.
234 /// 返回未知串行、无法访问设备或无效输入文本的错误。
235 pub fn open(&'_ self, serial: &str) -> Result<Camera<'_>> {
236 let serial = cstring(serial, "serial")?;
237 let mut camera = std::ptr::null_mut();
238 check(unsafe { sys::hik_camera_open(serial.as_ptr(), &mut camera) })?;
239 Ok(Camera {
240 inner: NonNull::new(camera).expect("native returned null camera"),
241 started: false,
242 recording: false,
243 frame_callback: None,
244 exception_callback: None,
245 event_callback: None,
246 _sdk: PhantomData,
247 })
248 }
249
250 /// Forces IPv4 settings on a GigE camera without opening its stream.
251 /// 强制在不打开GigE相机流的情况下设置IPv4。
252 ///
253 /// A successful call can make the device unreachable at its previous address.
254 /// 调用成功时,设备在之前的地址可能无法访问。
255 ///
256 /// # Errors
257 /// # 错误
258 /// Returns an error for non-GigE devices, unknown serials, or rejected settings.
259 /// 对于非 GigE 设备、未知序列号或拒绝设置,返回错误。
260 pub fn force_ip(
261 &self,
262 serial: &str,
263 ip: std::net::Ipv4Addr,
264 subnet: std::net::Ipv4Addr,
265 gateway: std::net::Ipv4Addr,
266 ) -> Result<()> {
267 let serial = cstring(serial, "serial")?;
268 check(unsafe {
269 sys::hik_force_ip(
270 serial.as_ptr(),
271 u32::from(ip),
272 u32::from(subnet),
273 u32::from(gateway),
274 )
275 })
276 }
277
278 /// Broadcasts a GigE Vision Action Command and returns device acknowledgements.
279 /// 广播GigEVision Action Command并返回设备确认。
280 ///
281 /// The keys and mask must match the Action Control nodes configured in each target camera.
282 /// 按键和掩码必须与每个目标相机配置的动作控制节点匹配。
283 /// This is memory-safe but can trigger multiple physical devices simultaneously.
284 /// 这对内存安全,但可以同时触发多个物理设备。
285 ///
286 /// # Errors
287 /// # 错误
288 /// Returns an error if the broadcast address is invalid for the C ABI or the SDK rejects
289 /// 如果广播地址对C ABI无效或SDK拒绝,则返回错误
290 /// the command.
291 /// 命令。
292 pub fn action_command(
293 &self,
294 device_key: u32,
295 group_key: u32,
296 group_mask: u32,
297 broadcast_address: &str,
298 timeout_ms: u32,
299 ) -> Result<Vec<ActionResult>> {
300 let address = cstring(broadcast_address, "broadcast address")?;
301 let blank = sys::HikActionResult {
302 device_address: [0; 16],
303 status: 0,
304 };
305 let mut results = vec![blank; 256];
306 let mut count = 0;
307 check(unsafe {
308 sys::hik_action_command(
309 device_key,
310 group_key,
311 group_mask,
312 address.as_ptr(),
313 timeout_ms,
314 results.as_mut_ptr(),
315 results.len(),
316 &mut count,
317 )
318 })?;
319 results.truncate(count.min(results.len()));
320 Ok(results
321 .into_iter()
322 .map(|r| ActionResult {
323 device_address: text(&r.device_address),
324 status: r.status,
325 })
326 .collect())
327 }
328}
329
330impl Drop for Sdk {
331 fn drop(&mut self) {
332 unsafe {
333 sys::hik_finalize();
334 }
335 }
336}
337
338/// Exclusive camera handle tied to the lifetime of an initialized [`Sdk`].
339/// 独占的相机句柄,绑定于初始化的Sdk的生命周期。
340///
341/// The handle closes automatically on drop. A camera may be moved to another thread, but its
342/// 句柄在析构时会自动关闭。相机可以被移动到另一个线程,但其
343/// methods require exclusive or shared access and therefore cannot race through safe Rust.
344/// 方法需要独占或共享访问,因此无法通过安全的Rust进行产生数据竞争。
345pub struct Camera<'sdk> {
346 inner: NonNull<std::ffi::c_void>,
347 started: bool,
348 recording: bool,
349 frame_callback: Option<Box<FrameCallbackContext>>,
350 exception_callback: Option<Box<ExceptionCallbackContext>>,
351 event_callback: Option<Box<EventCallbackContext>>,
352 _sdk: PhantomData<&'sdk Sdk>,
353}
354// SAFETY: the native handle is only accessed through methods borrowing `self`; no method exposes
355// 安全性:原生句柄仅通过借用“self”的方法访问;没有方法会暴露
356// the pointer, and callback contexts use thread-safe channels. The type deliberately is not Sync.
357// 指针和回调上下文使用线程安全通道。这种类型故意不是同步。
358unsafe impl Send for Camera<'_> {}
359
360impl Camera<'_> {
361 /// Starts image acquisition using the camera's current trigger configuration.
362 /// 开始使用相机当前触发配置进行图像采集。
363 ///
364 /// This method does not modify `TriggerMode`; configure it explicitly before starting.
365 /// 该方法不修改“触发模式”;开始前要明确配置。
366 ///
367 /// # Errors
368 /// # 错误
369 /// Returns an SDK error when acquisition cannot be started.
370 /// 当无法启动采集时返回 SDK 错误。
371 pub fn start(&mut self) -> Result<()> {
372 check(unsafe { sys::hik_camera_start(self.inner.as_ptr()) })?;
373 self.started = true;
374 Ok(())
375 }
376
377 /// Stops image acquisition. Calling it while already stopped is accepted by the wrapper.
378 /// 停止图像采集。在已经停止时调用它会被包装器接受。
379 ///
380 /// # Errors
381 /// # 错误
382 /// Returns an SDK error when the stream cannot be stopped cleanly.
383 /// 当流无法干净地停止时,会返回SDK错误。
384 pub fn stop(&mut self) -> Result<()> {
385 check(unsafe { sys::hik_camera_stop(self.inner.as_ptr()) })?;
386 self.started = false;
387 Ok(())
388 }
389
390 /// Waits for one frame and returns an owned image buffer.
391 /// 等待一帧后返回一个拥有的图像缓冲区。
392 ///
393 /// `timeout_ms` is the maximum SDK wait in milliseconds. Converted formats are produced by
394 /// “timeout_ms”是SDK的最大等待时间,单位是毫秒。转换格式由以下公司制作
395 /// the MVS pixel converter. Do not combine active polling with [`Self::frame_channel`].
396 /// MVS像素转换器。请勿将主动轮询与Self::frame_channel结合使用。
397 ///
398 /// # Errors
399 /// # 错误
400 /// Returns an error on timeout, transport failure, allocation failure, or unsupported pixel
401 /// 超时、传输失败、分配失败或不支持像素时返回错误
402 /// conversion.
403 /// 转换。
404 pub fn grab(&mut self, timeout_ms: u32, format: OutputFormat) -> Result<Frame> {
405 let mut raw = sys::HikFrame {
406 width: 0,
407 height: 0,
408 stride: 0,
409 pixel_format: 0,
410 frame_number: 0,
411 timestamp: 0,
412 gain: 0.0,
413 exposure_time: 0.0,
414 average_brightness: 0,
415 lost_packets: 0,
416 chunk_width: 0,
417 chunk_height: 0,
418 unparsed_chunk_count: 0,
419 data: std::ptr::null_mut(),
420 data_len: 0,
421 };
422 check(unsafe {
423 sys::hik_camera_grab(self.inner.as_ptr(), timeout_ms, format as i32, &mut raw)
424 })?;
425 Ok(Frame { raw })
426 }
427
428 /// Queries whether the SDK currently considers the physical device connected.
429 /// 查询SDK当前是否将物理设备视为已连接。
430 pub fn is_connected(&self) -> Result<bool> {
431 let mut value = 0;
432 check(unsafe { sys::hik_camera_is_connected(self.inner.as_ptr(), &mut value) })?;
433 Ok(value != 0)
434 }
435
436 /// Sets the number of frame-buffer nodes maintained by the MVS stream engine.
437 /// 设定MVS流引擎维护的帧缓冲节点数量。
438 ///
439 /// Must normally be called before [`Self::start`]. `count` must be greater than zero.
440 /// 通常必须在Self::start之前调用。“计数”必须大于零。
441 pub fn set_image_node_count(&mut self, count: u32) -> Result<()> {
442 check(unsafe { sys::hik_camera_set_image_node_count(self.inner.as_ptr(), count) })
443 }
444
445 /// Registers the official MVS image callback and returns a Rust receiver.
446 /// 注册官方MVS图像回调并返回Rust接收器。
447 ///
448 /// Every callback frame is copied into [`OwnedFrame`] before the SDK callback returns. This
449 /// 每个回调帧都会被复制到 OwnedFrame,然后 SDK 回调才返回。就是这样
450 /// makes receiving safe but allocates and copies once per frame. Register before starting.
451 /// 使接收安全,但每帧分配和复制一次。开始前请注册。
452 /// Dropping the receiver discards later frames without panicking across FFI.
453 /// 丢弃接收器可以丢弃后续帧,不会在FFI中panic。
454 pub fn frame_channel(&mut self) -> Result<mpsc::Receiver<OwnedFrame>> {
455 let (sender, receiver) = mpsc::channel();
456 let mut context = Box::new(FrameCallbackContext { sender });
457 check(unsafe {
458 sys::hik_camera_register_frame_callback(
459 self.inner.as_ptr(),
460 rust_frame_callback,
461 (&mut *context as *mut FrameCallbackContext).cast(),
462 )
463 })?;
464 self.frame_callback = Some(context);
465 Ok(receiver)
466 }
467
468 /// Registers the device exception callback and returns its event receiver.
469 /// 注册设备异常回调并返回其事件接收器。
470 ///
471 /// The most important event is [`ExceptionEvent::Disconnected`]. Register after opening and
472 /// 最重要的事件是 `ExceptionEvent::Disconnected`。请在打开相机后注册,
473 /// keep the camera alive while consuming the channel.
474 /// 并在接收事件期间保持相机存活。
475 pub fn exception_channel(&mut self) -> Result<mpsc::Receiver<ExceptionEvent>> {
476 let (sender, receiver) = mpsc::channel();
477 let mut context = Box::new(ExceptionCallbackContext { sender });
478 check(unsafe {
479 sys::hik_camera_register_exception_callback(
480 self.inner.as_ptr(),
481 rust_exception_callback,
482 (&mut *context as *mut ExceptionCallbackContext).cast(),
483 )
484 })?;
485 self.exception_callback = Some(context);
486 Ok(receiver)
487 }
488
489 /// Registers the camera event callback and returns owned event records through a channel.
490 /// 注册相机事件回调,并通过通道返回已拥有的事件记录。
491 ///
492 /// Event notifications must also be enabled in the camera's GenICam nodes.
493 /// 事件通知也必须在相机的 GenICam 节点中启用。
494 pub fn event_channel(&mut self) -> Result<mpsc::Receiver<CameraEvent>> {
495 let (sender, receiver) = mpsc::channel();
496 let mut context = Box::new(EventCallbackContext { sender });
497 check(unsafe {
498 sys::hik_camera_register_event_callback(
499 self.inner.as_ptr(),
500 rust_event_callback,
501 (&mut *context as *mut EventCallbackContext).cast(),
502 )
503 })?;
504 self.event_callback = Some(context);
505 Ok(receiver)
506 }
507
508 /// Reads cumulative GigE transport statistics for the current open/stream interval.
509 /// 读取当前打开/取流期间的累计GigE传输统计数据。
510 ///
511 /// # Errors
512 /// # 错误
513 /// USB cameras and unsupported transports return an SDK error.
514 /// USB相机和不支持的传输会返回SDK错误。
515 pub fn network_stats(&self) -> Result<NetworkStats> {
516 let mut stats = sys::HikNetworkStats {
517 received_bytes: 0,
518 lost_packets: 0,
519 lost_frames: 0,
520 received_frames: 0,
521 requested_resend_packets: 0,
522 resent_packets: 0,
523 };
524 check(unsafe { sys::hik_camera_network_stats(self.inner.as_ptr(), &mut stats) })?;
525 Ok(NetworkStats {
526 received_bytes: stats.received_bytes,
527 lost_packets: stats.lost_packets,
528 lost_frames: stats.lost_frames,
529 received_frames: stats.received_frames,
530 requested_resend_packets: stats.requested_resend_packets,
531 resent_packets: stats.resent_packets,
532 })
533 }
534
535 /// Encodes a frame to an image file using the MVS image encoder.
536 /// 使用MVS图像编码器将帧编码为图像文件。
537 ///
538 /// `quality` is used for JPEG and should be in `(50, 99]`; it is ignored by other formats.
539 /// “质量”用于JPEG,应在“(50, 99]'中;其他格式会忽略它。
540 /// Paths pass through the SDK's UTF-8/ANSI C interface and are subject to its platform limit.
541 /// 路径通过SDK的UTF-8/ANSI C接口,并受其平台限制。
542 ///
543 /// # Errors
544 /// # 错误
545 /// Returns an SDK error for unsupported source formats, invalid quality, or file I/O failure.
546 /// 返回SDK错误,原因是不支持的源格式、质量无效或文件I/O失败。
547 pub fn save_image(
548 &self,
549 frame: &Frame,
550 format: ImageFormat,
551 quality: u32,
552 path: &str,
553 ) -> Result<()> {
554 let path = cstring(path, "image path")?;
555 check(unsafe {
556 sys::hik_camera_save_image(
557 self.inner.as_ptr(),
558 &frame.raw,
559 format as i32,
560 quality,
561 path.as_ptr(),
562 )
563 })
564 }
565
566 /// Starts the MVS AVI recorder using metadata from `first_frame`.
567 /// 使用“first_frame”中的元数据启动MVS AVI录制器。
568 ///
569 /// `frame_rate` is frames per second and `bit_rate_kbps` is kilobits per second. Subsequent
570 /// “frame_rate”是每秒帧数,“bit_rate_kbps”是千比特每秒。后续
571 /// frames passed to [`Self::record_input`] must have compatible dimensions and pixel format.
572 /// 传递给Self::record_input的帧必须具有兼容的尺寸和像素格式。
573 ///
574 /// # Errors
575 /// # 错误
576 /// Returns an error for invalid recording parameters or an unavailable encoder.
577 /// 因录制参数无效或编码器不可用而返回错误。
578 pub fn record_start(
579 &mut self,
580 first_frame: &Frame,
581 frame_rate: f32,
582 bit_rate_kbps: u32,
583 path: &str,
584 ) -> Result<()> {
585 let path = cstring(path, "record path")?;
586 check(unsafe {
587 sys::hik_camera_record_start(
588 self.inner.as_ptr(),
589 &first_frame.raw,
590 frame_rate,
591 bit_rate_kbps,
592 path.as_ptr(),
593 )
594 })?;
595 self.recording = true;
596 Ok(())
597 }
598
599 /// Submits one acquired frame to an active recorder.
600 /// 将一帧获得的帧提交给活动录像器。
601 ///
602 /// # Errors
603 /// # 错误
604 /// Returns an error if recording is inactive or the frame is incompatible.
605 /// 如果录制处于非激活状态或帧不兼容,会返回错误。
606 pub fn record_input(&mut self, frame: &Frame) -> Result<()> {
607 check(unsafe { sys::hik_camera_record_input(self.inner.as_ptr(), &frame.raw) })
608 }
609
610 /// Finalizes the current AVI file. It is also attempted automatically on camera drop.
611 /// 最终确定当前的AVI文件。相机掉落时也会自动尝试。
612 pub fn record_stop(&mut self) -> Result<()> {
613 check(unsafe { sys::hik_camera_record_stop(self.inner.as_ptr()) })?;
614 self.recording = false;
615 Ok(())
616 }
617
618 /// Rotates a Mono8 or RGB/BGR packed frame through the MVS image processor.
619 /// 通过MVS图像处理器旋转一个Mono8或RGB/BGR填充的帧。
620 ///
621 /// The returned frame owns a newly allocated buffer.
622 /// 返回的帧拥有一个新分配的缓冲区。
623 pub fn rotate(&self, source: &Frame, angle: Rotation) -> Result<Frame> {
624 let mut output = empty_frame();
625 check(unsafe {
626 sys::hik_camera_rotate(self.inner.as_ptr(), &source.raw, angle as u32, &mut output)
627 })?;
628 Ok(Frame { raw: output })
629 }
630
631 /// Flips a Mono8 or RGB/BGR packed frame and returns a newly owned buffer.
632 /// 翻转一个Mono8或RGB/BGR填充的帧,返回一个新拥有的缓冲区。
633 pub fn flip(&self, source: &Frame, direction: FlipDirection) -> Result<Frame> {
634 let mut output = empty_frame();
635 check(unsafe {
636 sys::hik_camera_flip(
637 self.inner.as_ptr(),
638 &source.raw,
639 direction as u32,
640 &mut output,
641 )
642 })?;
643 Ok(Frame { raw: output })
644 }
645
646 /// Writes a floating-point GenICam node such as `ExposureTime` or `Gain`.
647 /// 写入浮点GenICam节点,如“ExposureTime”或“Gain”。
648 pub fn set_float(&mut self, name: &str, value: f32) -> Result<()> {
649 let name = cstring(name, "parameter name")?;
650 check(unsafe { sys::hik_camera_set_float(self.inner.as_ptr(), name.as_ptr(), value) })
651 }
652
653 /// Reads a floating-point GenICam node together with its allowed range.
654 /// 读取浮点 GenICam 节点及其允许范围。
655 pub fn get_float(&self, name: &str) -> Result<FloatValue> {
656 let name = cstring(name, "parameter name")?;
657 let mut v = sys::HikFloatValue {
658 current: 0.0,
659 minimum: 0.0,
660 maximum: 0.0,
661 };
662 check(unsafe { sys::hik_camera_get_float(self.inner.as_ptr(), name.as_ptr(), &mut v) })?;
663 Ok(FloatValue {
664 current: v.current,
665 minimum: v.minimum,
666 maximum: v.maximum,
667 })
668 }
669
670 /// Writes an integer GenICam node such as `Width`, `Height`, or an Action key.
671 /// 写入整数GenICam节点,如“Width”、“Height”或Action键。
672 pub fn set_int(&mut self, name: &str, value: i64) -> Result<()> {
673 let name = cstring(name, "parameter name")?;
674 check(unsafe { sys::hik_camera_set_int(self.inner.as_ptr(), name.as_ptr(), value) })
675 }
676
677 /// Reads an integer GenICam node and its minimum, maximum, and increment.
678 /// 读取整数GenICam节点及其最小值、最大值和增量。
679 pub fn get_int(&self, name: &str) -> Result<IntValue> {
680 let name = cstring(name, "parameter name")?;
681 let mut v = sys::HikIntValue {
682 current: 0,
683 minimum: 0,
684 maximum: 0,
685 increment: 0,
686 };
687 check(unsafe { sys::hik_camera_get_int(self.inner.as_ptr(), name.as_ptr(), &mut v) })?;
688 Ok(IntValue {
689 current: v.current,
690 minimum: v.minimum,
691 maximum: v.maximum,
692 increment: v.increment,
693 })
694 }
695
696 /// Selects an enumeration node by symbolic name, for example `TriggerMode = On`.
697 /// 通过符号名称选择枚举节点,例如“TriggerMode = On”。
698 pub fn set_enum(&mut self, name: &str, value: &str) -> Result<()> {
699 let name = cstring(name, "parameter name")?;
700 let value = cstring(value, "parameter value")?;
701 check(unsafe {
702 sys::hik_camera_set_enum(self.inner.as_ptr(), name.as_ptr(), value.as_ptr())
703 })
704 }
705
706 /// Returns the symbolic name of the current enumeration value.
707 /// 返回当前枚举值的符号名称。
708 pub fn get_enum(&self, name: &str) -> Result<String> {
709 let name = cstring(name, "parameter name")?;
710 let mut required = 0;
711 check(unsafe {
712 sys::hik_camera_get_enum(
713 self.inner.as_ptr(),
714 name.as_ptr(),
715 std::ptr::null_mut(),
716 0,
717 &mut required,
718 )
719 })?;
720 let mut value = vec![0i8; required];
721 check(unsafe {
722 sys::hik_camera_get_enum(
723 self.inner.as_ptr(),
724 name.as_ptr(),
725 value.as_mut_ptr(),
726 value.len(),
727 &mut required,
728 )
729 })?;
730 Ok(unsafe { CStr::from_ptr(value.as_ptr()) }
731 .to_string_lossy()
732 .into_owned())
733 }
734
735 /// Writes a Boolean GenICam node such as `ChunkModeActive`.
736 /// 写入布尔 GenICam 节点,如 'ChunkModeActive'。
737 pub fn set_bool(&mut self, name: &str, value: bool) -> Result<()> {
738 let name = cstring(name, "parameter name")?;
739 check(unsafe {
740 sys::hik_camera_set_bool(self.inner.as_ptr(), name.as_ptr(), u8::from(value))
741 })
742 }
743
744 /// Reads a Boolean GenICam node.
745 /// 读取一个布尔GenICam节点。
746 pub fn get_bool(&self, name: &str) -> Result<bool> {
747 let name = cstring(name, "parameter name")?;
748 let mut value = 0;
749 check(unsafe { sys::hik_camera_get_bool(self.inner.as_ptr(), name.as_ptr(), &mut value) })?;
750 Ok(value != 0)
751 }
752
753 /// Writes a string GenICam node such as `DeviceUserID`.
754 /// 写入字符串GenICam节点,如“DeviceUserID”。
755 pub fn set_string(&mut self, name: &str, value: &str) -> Result<()> {
756 let name = cstring(name, "parameter name")?;
757 let value = cstring(value, "parameter value")?;
758 check(unsafe {
759 sys::hik_camera_set_string(self.inner.as_ptr(), name.as_ptr(), value.as_ptr())
760 })
761 }
762
763 /// Reads a string GenICam node into an owned UTF-8-lossy Rust string.
764 /// 将字符串GenICam节点读取到拥有的UTF-8有损Rust字符串中。
765 pub fn get_string(&self, name: &str) -> Result<String> {
766 let name = cstring(name, "parameter name")?;
767 let mut required = 0;
768 check(unsafe {
769 sys::hik_camera_get_string(
770 self.inner.as_ptr(),
771 name.as_ptr(),
772 std::ptr::null_mut(),
773 0,
774 &mut required,
775 )
776 })?;
777 let mut value = vec![0i8; required];
778 check(unsafe {
779 sys::hik_camera_get_string(
780 self.inner.as_ptr(),
781 name.as_ptr(),
782 value.as_mut_ptr(),
783 value.len(),
784 &mut required,
785 )
786 })?;
787 Ok(unsafe { CStr::from_ptr(value.as_ptr()) }
788 .to_string_lossy()
789 .into_owned())
790 }
791
792 /// Executes a command node such as `TriggerSoftware` or `UserSetSave` once.
793 /// 执行一次命令节点,如“TriggerSoftware”或“UserSetSave”。
794 pub fn command(&mut self, name: &str) -> Result<()> {
795 let name = cstring(name, "command")?;
796 check(unsafe { sys::hik_camera_command(self.inner.as_ptr(), name.as_ptr()) })
797 }
798
799 /// Saves the camera's GenICam feature configuration to a host file.
800 /// 将相机的GenICamFeature 配置保存到主机文件中。
801 pub fn feature_save(&self, path: &str) -> Result<()> {
802 let path = cstring(path, "feature path")?;
803 check(unsafe { sys::hik_camera_feature_save(self.inner.as_ptr(), path.as_ptr()) })
804 }
805
806 /// Loads GenICam features from a host file and applies them to the camera.
807 /// 从主机文件加载GenICam的功能并应用到相机上。
808 ///
809 /// This can change acquisition, trigger, network, and image-format settings.
810 /// 这可以改变采集、触发、网络和图像格式的设置。
811 pub fn feature_load(&mut self, path: &str) -> Result<()> {
812 let path = cstring(path, "feature path")?;
813 check(unsafe { sys::hik_camera_feature_load(self.inner.as_ptr(), path.as_ptr()) })
814 }
815
816 /// Saves current settings into a camera-resident UserSet slot.
817 /// 将当前设置保存到相机驻留的UserSet插槽中。
818 pub fn user_set_save(&mut self, user_set: &str) -> Result<()> {
819 self.set_enum("UserSetSelector", user_set)?;
820 self.command("UserSetSave")
821 }
822
823 /// Loads a camera-resident UserSet slot immediately.
824 /// 立即加载一个相机内置的 UserSet 插槽。
825 pub fn user_set_load(&mut self, user_set: &str) -> Result<()> {
826 self.set_enum("UserSetSelector", user_set)?;
827 self.command("UserSetLoad")
828 }
829
830 /// Selects the UserSet loaded by the camera on its next startup.
831 /// 在相机下一次启动时选择加载的用户集。
832 pub fn user_set_default(&mut self, user_set: &str) -> Result<()> {
833 self.set_enum("UserSetDefault", user_set)
834 }
835}
836
837impl Drop for Camera<'_> {
838 fn drop(&mut self) {
839 unsafe {
840 if self.recording {
841 sys::hik_camera_record_stop(self.inner.as_ptr());
842 }
843 if self.started {
844 sys::hik_camera_stop(self.inner.as_ptr());
845 }
846 sys::hik_camera_close(self.inner.as_ptr());
847 }
848 }
849}
850
851/// Integer GenICam node value and constraints.
852/// 整数GenICam节点值与约束。
853#[derive(Debug, Clone, Copy)]
854pub struct IntValue {
855 /// Current node value.
856 /// 当前节点值。
857 pub current: i64,
858 /// Smallest permitted value.
859 /// 最小允许值。
860 pub minimum: i64,
861 /// Largest permitted value.
862 /// 最大允许值。
863 pub maximum: i64,
864 /// Required step between valid values; zero if the device does not report one.
865 /// 有效值之间的必要步进;如果设备没有报告,则为零。
866 pub increment: i64,
867}
868/// Floating-point GenICam node value and constraints.
869/// 浮点 GenICam 节点值与约束。
870#[derive(Debug, Clone, Copy)]
871pub struct FloatValue {
872 /// Current node value.
873 /// 当前节点值。
874 pub current: f32,
875 /// Smallest permitted value.
876 /// 最小允许值。
877 pub minimum: f32,
878 /// Largest permitted value.
879 /// 最大允许值。
880 pub maximum: f32,
881}
882
883/// Four-component version number reported by `MV_CC_GetSDKVersion`.
884/// 四组件版本号由“MV_CC_GetSDKVersion”报告。
885#[derive(Debug, Clone, Copy, PartialEq, Eq)]
886pub struct SdkVersion {
887 /// Major version component.
888 /// 主版本号。
889 pub major: u8,
890 /// Minor version component.
891 /// 小版本组件。
892 pub minor: u8,
893 /// Patch version component.
894 /// 补丁版本组件。
895 pub patch: u8,
896 /// Build or revision component.
897 /// 构建或修订组件。
898 pub build: u8,
899 /// Original packed 32-bit SDK value.
900 /// 原始打包的32位SDK值。
901 pub raw: u32,
902}
903
904/// Acknowledgement returned by one device after an Action Command broadcast.
905/// 在Action Command广播后,一台设备返回了确认。
906#[derive(Debug, Clone)]
907pub struct ActionResult {
908 /// Device IPv4 address formatted by the MVS SDK.
909 /// 设备IPv4地址由MVS SDK格式化。
910 pub device_address: String,
911 /// GigE Vision acknowledgement status; zero indicates success.
912 /// GigE Vision确认状态;零表示成功。
913 pub status: i32,
914}
915impl SdkVersion {
916 fn from_raw(raw: u32) -> Self {
917 Self {
918 major: (raw >> 24) as u8,
919 minor: (raw >> 16) as u8,
920 patch: (raw >> 8) as u8,
921 build: raw as u8,
922 raw,
923 }
924 }
925}
926impl std::fmt::Display for SdkVersion {
927 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928 write!(
929 f,
930 "{}.{}.{}.{}",
931 self.major, self.minor, self.patch, self.build
932 )
933 }
934}
935
936/// Pixel representation requested from [`Camera::grab`].
937/// 像素表示请求来自Camera::grab。
938#[repr(i32)]
939#[derive(Debug, Clone, Copy, PartialEq, Eq)]
940pub enum OutputFormat {
941 /// Preserve the camera's native pixel format and encoded layout.
942 /// 保持相机的原始像素格式和编码布局。
943 Raw = 0,
944 /// Convert to one unsigned 8-bit luminance channel per pixel.
945 /// 转换为每个像素一个无符号的8位亮度通道。
946 Mono8 = 1,
947 /// Convert to packed blue-green-red bytes, three bytes per pixel.
948 /// 转换为打包蓝绿红字节,每个像素三字节。
949 Bgr8 = 2,
950}
951
952/// File encoding used by [`Camera::save_image`].
953/// 文件编码由Camera::save_image使用。
954#[repr(i32)]
955#[derive(Debug, Clone, Copy, PartialEq, Eq)]
956pub enum ImageFormat {
957 /// Uncompressed Windows bitmap.
958 /// 未压缩的Windows位图。
959 Bmp = 1,
960 /// Lossy JPEG encoding controlled by the quality argument.
961 /// 由质量参数控制的有损JPEG编码。
962 Jpeg = 2,
963 /// Lossless PNG encoding.
964 /// 无损PNG编码。
965 Png = 3,
966 /// TIFF encoding.
967 /// TIFF编码。
968 Tiff = 4,
969}
970
971/// Clockwise rotation angle for [`Camera::rotate`].
972/// 顺时针旋转角度 Camera::rotate。
973#[repr(u32)]
974#[derive(Debug, Clone, Copy, PartialEq, Eq)]
975pub enum Rotation {
976 /// Rotate clockwise by 90 degrees.
977 /// 顺时针旋转90度。
978 Degrees90 = 1,
979 /// Rotate by 180 degrees.
980 /// 旋转180度。
981 Degrees180 = 2,
982 /// Rotate clockwise by 270 degrees.
983 /// 顺时针旋转270度。
984 Degrees270 = 3,
985}
986
987/// Axis used by [`Camera::flip`].
988/// 轴线由Camera::flip使用。
989#[repr(u32)]
990#[derive(Debug, Clone, Copy, PartialEq, Eq)]
991pub enum FlipDirection {
992 /// Mirror top to bottom.
993 /// 从上到下镜像。
994 Vertical = 1,
995 /// Mirror left to right.
996 /// 从左到右镜像。
997 Horizontal = 2,
998}
999
1000/// Owned frame returned by synchronous acquisition and image transforms.
1001/// 拥有帧通过同步采集和图像转换返回。
1002///
1003/// The backing allocation is owned by the native wrapper and is released on drop. Use
1004/// 备份分配归原生封装者所有,并直接释放。用途
1005/// [`Self::data`] to borrow it; the pointer is never exposed by the safe API.
1006/// Self::d ata借用;该指针从未被安全API暴露。
1007pub struct Frame {
1008 raw: sys::HikFrame,
1009}
1010impl Frame {
1011 /// Image width in pixels.
1012 /// 图像宽度以像素为单位。
1013 pub fn width(&self) -> u32 {
1014 self.raw.width
1015 }
1016 /// Image height in pixels.
1017 /// 图像高度(像素单位)。
1018 pub fn height(&self) -> u32 {
1019 self.raw.height
1020 }
1021 /// Number of bytes between adjacent image rows.
1022 /// 相邻图像行之间的字节数。
1023 pub fn stride(&self) -> u32 {
1024 self.raw.stride
1025 }
1026 /// Raw numeric value from Hikrobot's `MvGvspPixelType` enumeration.
1027 /// 来自Hikrobot的“MvGvspPixelType”枚举中的原始数值。
1028 pub fn pixel_format(&self) -> u32 {
1029 self.raw.pixel_format
1030 }
1031 /// Monotonic device frame sequence number.
1032 /// 单调递增的设备帧序号。
1033 pub fn frame_number(&self) -> u64 {
1034 self.raw.frame_number
1035 }
1036 /// Device timestamp assembled from the SDK's high and low words.
1037 /// 设备时间戳由SDK的高低字组成。
1038 pub fn timestamp(&self) -> u64 {
1039 self.raw.timestamp
1040 }
1041 /// Returns parsed watermark and Chunk fields reported with this frame.
1042 /// 返回时,解析水印和块字段报告,使用此框架。
1043 pub fn chunk(&self) -> ChunkMetadata {
1044 ChunkMetadata {
1045 gain: self.raw.gain,
1046 exposure_time: self.raw.exposure_time,
1047 average_brightness: self.raw.average_brightness,
1048 lost_packets: self.raw.lost_packets,
1049 width: self.raw.chunk_width,
1050 height: self.raw.chunk_height,
1051 unparsed_count: self.raw.unparsed_chunk_count,
1052 }
1053 }
1054 /// Borrows the image bytes for the lifetime of this frame.
1055 /// 借用该帧寿命内的图像字节。
1056 pub fn data(&self) -> &[u8] {
1057 // SAFETY: successful native frame creation guarantees a live allocation of `data_len`
1058 // 安全性:成功的原生帧创建保证了“data_len”的实时分配
1059 // bytes. `Frame` owns that allocation exclusively and releases it only in `Drop`.
1060 // 字节。“Frame”独家拥有该分配,仅在“Drop”中释放。
1061 unsafe { slice::from_raw_parts(self.raw.data, self.raw.data_len) }
1062 }
1063}
1064
1065fn empty_frame() -> sys::HikFrame {
1066 sys::HikFrame {
1067 width: 0,
1068 height: 0,
1069 stride: 0,
1070 pixel_format: 0,
1071 frame_number: 0,
1072 timestamp: 0,
1073 gain: 0.0,
1074 exposure_time: 0.0,
1075 average_brightness: 0,
1076 lost_packets: 0,
1077 chunk_width: 0,
1078 chunk_height: 0,
1079 unparsed_chunk_count: 0,
1080 data: std::ptr::null_mut(),
1081 data_len: 0,
1082 }
1083}
1084
1085/// Frame watermark and Chunk fields parsed by the MVS SDK.
1086/// 帧水印和块字段由 MVS SDK 解析。
1087///
1088/// A zero value may mean either that the camera reported zero or that the corresponding Chunk
1089/// 零值可能表示相机报告零值,或对应的块
1090/// entry was not enabled. [`Self::unparsed_count`] reports vendor-specific chunks not decoded
1091/// 进入未被启用。self::unparsed_count 报告供应商特定Chunk未解码
1092/// into the standard fields.
1093/// 进入标准字段。
1094#[derive(Debug, Clone, Copy, Default)]
1095pub struct ChunkMetadata {
1096 /// Gain reported for this frame, in the device-defined unit.
1097 /// 该帧在设备定义单元内报告增益。
1098 pub gain: f32,
1099 /// Exposure time reported for this frame, normally microseconds.
1100 /// 本帧的曝光时间通常为微秒。
1101 pub exposure_time: f32,
1102 /// Device-computed average brightness.
1103 /// 设备计算的平均亮度。
1104 pub average_brightness: u32,
1105 /// Packets lost while receiving this individual frame.
1106 /// 在接收该单独帧时丢失的数据包。
1107 pub lost_packets: u32,
1108 /// Width reported by the Chunk payload.
1109 /// 块状载荷报告的宽度。
1110 pub width: u32,
1111 /// Height reported by the Chunk payload.
1112 /// Chunk有效载荷报告的高度。
1113 pub height: u32,
1114 /// Number of Chunk entries not parsed by the SDK.
1115 /// SDK 未解析的Chunk条目数量。
1116 pub unparsed_count: u32,
1117}
1118impl Drop for Frame {
1119 fn drop(&mut self) {
1120 // SAFETY: `raw` was initialized by the wrapper and has not been released elsewhere; the
1121 // 安全性:“RAW”由包装初始化,未在其他地方释放;该
1122 // safe API never exposes a mutable pointer or implements Clone for `Frame`.
1123 // safe API 从不暴露可变指针,也不会为“Frame”实现克隆。
1124 unsafe {
1125 sys::hik_frame_release(&mut self.raw);
1126 }
1127 }
1128}
1129
1130/// Rust-owned frame delivered by [`Camera::frame_channel`].
1131/// 由 `Camera::frame_channel` 交付、所有权属于 Rust 的帧。
1132///
1133/// Unlike [`Frame`], all bytes live in a normal [`Vec`] and may be retained after the camera is
1134/// 与[“Frame”]不同,所有字节都存在于正常的Vec中,并且可以在相机
1135/// stopped or dropped.
1136/// 停下来或掉落。
1137#[derive(Debug, Clone)]
1138pub struct OwnedFrame {
1139 /// Image width in pixels.
1140 /// 图像宽度以像素为单位。
1141 pub width: u32,
1142 /// Image height in pixels.
1143 /// 图像高度(像素单位)。
1144 pub height: u32,
1145 /// Bytes between adjacent rows.
1146 /// 相邻行之间的字节。
1147 pub stride: u32,
1148 /// Raw `MvGvspPixelType` numeric value.
1149 /// 原始数值为“MvGvspPixelType”。
1150 pub pixel_format: u32,
1151 /// Device frame sequence number.
1152 /// 设备帧序列号。
1153 pub frame_number: u64,
1154 /// Device timestamp.
1155 /// 设备时间戳。
1156 pub timestamp: u64,
1157 /// Owned image bytes copied inside the callback.
1158 /// 回调内复制的图像字节。
1159 pub data: Vec<u8>,
1160}
1161
1162/// Asynchronous device exception delivered by [`Camera::exception_channel`].
1163/// 异步设备异常由Camera::exception_channel提供。
1164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1165pub enum ExceptionEvent {
1166 /// The camera disconnected (`MV_EXCEPTION_DEV_DISCONNECT`).
1167 /// 相机断开(“MV_EXCEPTION_DEV_DISCONNECT”)。
1168 Disconnected,
1169 /// Another vendor exception identified by its raw message type.
1170 /// 另一个厂商异常,因其原始消息类型被识别。
1171 Other(u32),
1172}
1173
1174/// Owned camera event delivered by [`Camera::event_channel`].
1175/// 由Camera::event_channel提供自有相机事件。
1176#[derive(Debug, Clone)]
1177pub struct CameraEvent {
1178 /// GenICam event name, for example an exposure-end event.
1179 /// GenICam 事件名称,例如曝光结束事件。
1180 pub name: String,
1181 /// Numeric event identifier.
1182 /// 数字事件标识符。
1183 pub event_id: u16,
1184 /// Stream channel that produced the event.
1185 /// 产生该事件的流通道。
1186 pub stream_channel: u16,
1187 /// Associated block/frame identifier when supplied by firmware.
1188 /// 固件提供时,关联的块/帧标识符。
1189 pub block_id: u64,
1190 /// Device event timestamp.
1191 /// 设备事件时间戳。
1192 pub timestamp: u64,
1193}
1194
1195/// Cumulative GigE stream health counters returned by [`Camera::network_stats`].
1196/// 累计GigE流的健康状态计数器由Camera::network_stats返回。
1197#[derive(Debug, Clone, Copy, Default)]
1198pub struct NetworkStats {
1199 /// Total payload bytes received during the current stream interval.
1200 /// 当前流间隔内接收的总有效载荷字节数。
1201 pub received_bytes: i64,
1202 /// Number of missing network packets detected.
1203 /// 检测到的网络数据包缺失数量。
1204 pub lost_packets: i64,
1205 /// Number of incomplete frames discarded.
1206 /// 丢弃的未完成帧数。
1207 pub lost_frames: u32,
1208 /// Number of frames received by the network layer.
1209 /// 网络层接收的帧数。
1210 pub received_frames: u32,
1211 /// Number of packet retransmissions requested by the receiver.
1212 /// 接收方请求的数据包重传次数。
1213 pub requested_resend_packets: i64,
1214 /// Number of retransmitted packets actually received.
1215 /// 实际接收的重传数据包数量。
1216 pub resent_packets: i64,
1217}
1218
1219struct FrameCallbackContext {
1220 sender: mpsc::Sender<OwnedFrame>,
1221}
1222struct ExceptionCallbackContext {
1223 sender: mpsc::Sender<ExceptionEvent>,
1224}
1225struct EventCallbackContext {
1226 sender: mpsc::Sender<CameraEvent>,
1227}
1228
1229unsafe extern "C" fn rust_frame_callback(frame: *const sys::HikFrame, user: *mut std::ffi::c_void) {
1230 if frame.is_null() || user.is_null() {
1231 return;
1232 }
1233 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1234 // SAFETY: the C++ trampoline supplies both pointers and keeps them valid for this call.
1235 // 安全性:C++ 中转函数提供这两个指针,并保持它们在本次调用中的有效性。
1236 let frame = unsafe { &*frame };
1237 if frame.data.is_null() {
1238 return;
1239 }
1240 // SAFETY: `user` points to the boxed context retained by `Camera` until after stream stop.
1241 // 安全:'用户'指向由'相机'保留的装箱的上下文,直到直播停止后。
1242 let context = unsafe { &*(user as *const FrameCallbackContext) };
1243 let owned = OwnedFrame {
1244 width: frame.width,
1245 height: frame.height,
1246 stride: frame.stride,
1247 pixel_format: frame.pixel_format,
1248 frame_number: frame.frame_number,
1249 timestamp: frame.timestamp,
1250 // SAFETY: MVS guarantees the callback buffer for the duration of this callback. The
1251 // 安全性:MVS保证回调缓冲区在回调期间的存在。该
1252 // immediate copy ensures no borrowed SDK memory reaches the receiver.
1253 // 即时复制确保借用的SDK内存不会到达接收端。
1254 data: unsafe { slice::from_raw_parts(frame.data, frame.data_len) }.to_vec(),
1255 };
1256 let _ = context.sender.send(owned);
1257 }));
1258}
1259
1260unsafe extern "C" fn rust_exception_callback(message_type: u32, user: *mut std::ffi::c_void) {
1261 if user.is_null() {
1262 return;
1263 }
1264 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1265 // SAFETY: `user` is the boxed context stored by `Camera` until native close completes.
1266 // 安全:“用户”是“Camera”存储的装箱的上下文,直到原生关闭完成。
1267 let context = unsafe { &*(user as *const ExceptionCallbackContext) };
1268 let event = if message_type == 0x0000_8001 {
1269 ExceptionEvent::Disconnected
1270 } else {
1271 ExceptionEvent::Other(message_type)
1272 };
1273 let _ = context.sender.send(event);
1274 }));
1275}
1276
1277unsafe extern "C" fn rust_event_callback(event: *const sys::HikEvent, user: *mut std::ffi::c_void) {
1278 if event.is_null() || user.is_null() {
1279 return;
1280 }
1281 let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1282 // SAFETY: both pointers originate from the C++ callback trampoline and remain valid for
1283 // 安全:这两个指针都来自C++回调中转函数,并且在
1284 // this invocation; all event fields are copied before returning.
1285 // 本次调用;所有事件字段在返回前都会被复制。
1286 let event = unsafe { &*event };
1287 // SAFETY: the boxed context is retained by `Camera` until native close completes.
1288 // 安全:框内上下文由“相机”保留,直到原生关闭完成。
1289 let context = unsafe { &*(user as *const EventCallbackContext) };
1290 let owned = CameraEvent {
1291 name: text(&event.name),
1292 event_id: event.event_id,
1293 stream_channel: event.stream_channel,
1294 block_id: event.block_id,
1295 timestamp: event.timestamp,
1296 };
1297 let _ = context.sender.send(owned);
1298 }));
1299}