refactor: 重构视频采集状态与错误分类公共逻辑

This commit is contained in:
mofeng-git
2026-05-01 17:56:56 +08:00
parent d82c863f40
commit 0d47d8395d
8 changed files with 173 additions and 124 deletions

View File

@@ -0,0 +1,66 @@
//! Shared capture status and error classification helpers.
use std::io;
use crate::video::SignalStatus;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaptureIoErrorKind {
DeviceLost,
TransientSignal { status: Option<SignalStatus> },
Other,
}
pub fn signal_status_from_capture_kind(kind: &str) -> SignalStatus {
SignalStatus::from_str(kind).unwrap_or(SignalStatus::NoSignal)
}
pub fn classify_capture_io_error(err: &io::Error) -> CaptureIoErrorKind {
match err.raw_os_error() {
// ENXIO / ENODEV / ESHUTDOWN: the device node or endpoint is gone.
Some(6) | Some(19) | Some(108) => CaptureIoErrorKind::DeviceLost,
// EIO / EPIPE: source or transport glitched; EPROTO is common for UVC USB.
Some(5) | Some(32) => CaptureIoErrorKind::TransientSignal { status: None },
Some(71) => CaptureIoErrorKind::TransientSignal {
status: Some(SignalStatus::UvcUsbError),
},
_ => CaptureIoErrorKind::Other,
}
}
pub fn capture_error_log_key(err: &io::Error) -> String {
let message = err.to_string();
if message.contains("dqbuf failed") && message.contains("EINVAL") {
"capture_dqbuf_einval".to_string()
} else if message.contains("dqbuf failed") {
"capture_dqbuf".to_string()
} else {
format!("capture_{:?}", err.kind())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_known_signal_status_strings() {
assert_eq!(
signal_status_from_capture_kind("out_of_range"),
SignalStatus::OutOfRange
);
assert_eq!(
signal_status_from_capture_kind("unknown"),
SignalStatus::NoSignal
);
}
#[test]
fn classifies_source_change_log_keys() {
let err = io::Error::other("dqbuf failed: EINVAL");
assert_eq!(capture_error_log_key(&err), "capture_dqbuf_einval");
let err = io::Error::new(io::ErrorKind::TimedOut, "capture timeout");
assert_eq!(capture_error_log_key(&err), "capture_TimedOut");
}
}

View File

@@ -3,6 +3,7 @@
//! This module provides V4L2 video capture, encoding, and streaming functionality.
pub(crate) mod capture_limits;
pub(crate) mod capture_status;
pub mod codec_constraints;
pub mod convert;
pub mod csi_bridge;

View File

@@ -44,6 +44,10 @@ const ENCODE_ERROR_THROTTLE_SECS: u64 = 5;
use crate::error::{AppError, Result};
use crate::utils::LogThrottler;
use crate::video::capture_limits::{should_validate_jpeg_frame, MIN_CAPTURE_FRAME_SIZE};
use crate::video::capture_status::{
capture_error_log_key, classify_capture_io_error, signal_status_from_capture_kind,
CaptureIoErrorKind,
};
use crate::video::csi_bridge::{self, ProbeResult};
use crate::video::device::parse_bridge_kind;
use crate::video::encoder::registry::{EncoderBackend, VideoEncoderType};
@@ -586,7 +590,7 @@ impl SharedVideoPipeline {
debug!(
"Pre-probe: no signal — encoder uses configured geometry until capture opens"
);
let status = SignalStatus::from_str(&kind).unwrap_or(SignalStatus::NoSignal);
let status = signal_status_from_capture_kind(&kind);
self.notify_state(PipelineStateNotification::no_signal(
status,
Some(Duration::from_secs(2).as_millis() as u64),
@@ -757,7 +761,7 @@ impl SharedVideoPipeline {
kind
);
pipeline.notify_state(PipelineStateNotification::no_signal(
SignalStatus::from_str(&kind).unwrap_or(SignalStatus::NoSignal),
signal_status_from_capture_kind(&kind),
Some(CSI_BRIDGE_NOSIGNAL_INTERVAL_MS),
));
}
@@ -800,9 +804,7 @@ impl SharedVideoPipeline {
Ok(s) => OpenResult::Opened(s),
Err(AppError::CaptureNoSignal { kind }) => {
debug!("Capture soft-restart: still no signal ({})", kind);
OpenResult::NoSignal(
SignalStatus::from_str(&kind).unwrap_or(SignalStatus::NoSignal),
)
OpenResult::NoSignal(signal_status_from_capture_kind(&kind))
}
Err(e) => {
error!("Capture soft-restart failed: {}", e);
@@ -819,17 +821,6 @@ impl SharedVideoPipeline {
let capture_error_throttler = LogThrottler::with_secs(5);
let mut suppressed_capture_errors: HashMap<String, u64> = HashMap::new();
let classify_capture_error = |err: &std::io::Error| -> String {
let message = err.to_string();
if message.contains("dqbuf failed") && message.contains("EINVAL") {
"capture_dqbuf_einval".to_string()
} else if message.contains("dqbuf failed") {
"capture_dqbuf".to_string()
} else {
format!("capture_{:?}", err.kind())
}
};
while pipeline.running_flag.load(Ordering::Acquire) {
let subscriber_count = pipeline.subscriber_count();
if subscriber_count == 0 {
@@ -1121,30 +1112,39 @@ impl SharedVideoPipeline {
// EIO (5) / EPIPE (32) / EPROTO (71) in next_into generally
// mean the source or UVC USB transport glitched mid-stream.
// Tear down the stream and let the open loop re-probe.
let os = e.raw_os_error();
if matches!(os, Some(5) | Some(32) | Some(71)) {
if os == Some(71) {
warn!(
match classify_capture_io_error(&e) {
CaptureIoErrorKind::TransientSignal { status } => {
if status == Some(SignalStatus::UvcUsbError) {
warn!(
"Capture transient error (EPROTO/-71, often UVC USB): {} — soft-restart",
e
);
pipeline.notify_state(
PipelineStateNotification::no_signal(
SignalStatus::UvcUsbError,
Some(Duration::from_secs(2).as_millis() as u64),
),
);
} else {
warn!(
"Capture transient error ({}), closing stream for \
pipeline.notify_state(
PipelineStateNotification::no_signal(
SignalStatus::UvcUsbError,
Some(Duration::from_secs(2).as_millis() as u64),
),
);
} else {
warn!(
"Capture transient error ({}), closing stream for \
soft-restart",
e
);
e
);
}
stream = None;
continue;
}
stream = None;
continue;
CaptureIoErrorKind::DeviceLost => {
error!("Capture device lost: {}", e);
let _ = pipeline.running.send(false);
pipeline.running_flag.store(false, Ordering::Release);
let _ = frame_seq_tx.send(sequence.wrapping_add(1));
break;
}
CaptureIoErrorKind::Other => {}
}
let key = classify_capture_error(&e);
let key = capture_error_log_key(&e);
if capture_error_throttler.should_log(&key) {
let suppressed =
suppressed_capture_errors.remove(&key).unwrap_or(0);

View File

@@ -23,6 +23,10 @@ use crate::events::{EventBus, SystemEvent};
use crate::stream::MjpegStreamHandler;
use crate::utils::LogThrottler;
use crate::video::capture_limits::{should_validate_jpeg_frame, MIN_CAPTURE_FRAME_SIZE};
use crate::video::capture_status::{
capture_error_log_key, classify_capture_io_error, signal_status_from_capture_kind,
CaptureIoErrorKind,
};
use crate::video::v4l2r_capture::{is_source_changed_error, BridgeContext, V4l2rCaptureStream};
/// Streamer configuration
@@ -907,8 +911,7 @@ impl Streamer {
// "no signal" overlay, update the state with the
// fine-grained reason, and let the outer 'session
// loop back off before the next retry.
let status = crate::video::SignalStatus::from_str(&kind)
.unwrap_or(crate::video::SignalStatus::NoSignal);
let status = signal_status_from_capture_kind(&kind);
debug!(
"CSI open probe reports no signal ({:?}), will soft-restart",
status
@@ -989,17 +992,6 @@ impl Streamer {
let capture_error_throttler = LogThrottler::with_secs(5);
let mut suppressed_capture_errors: HashMap<String, u64> = HashMap::new();
let classify_capture_error = |err: &std::io::Error| -> String {
let message = err.to_string();
if message.contains("dqbuf failed") && message.contains("EINVAL") {
"capture_dqbuf_einval".to_string()
} else if message.contains("dqbuf failed") {
"capture_dqbuf".to_string()
} else {
format!("capture_{:?}", err.kind())
}
};
// None = signal is present; Some(Instant) = when signal was first lost.
let mut no_signal_since: Option<std::time::Instant> = None;
// Whether the inner 'capture loop should trigger a soft restart.
@@ -1078,59 +1070,60 @@ impl Streamer {
// when the source glitches or re-locks; those are
// treated as NoSignal + soft-restart so we recover
// in ~1 s instead of the 1 s recovery-poll loop.
let os_err = e.raw_os_error();
let is_device_lost = matches!(os_err, Some(6) | Some(19) | Some(108));
let is_transient_signal_error =
matches!(os_err, Some(5) | Some(32) | Some(71));
if is_device_lost {
error!("Video device lost: {} - {}", device_path.display(), e);
go_offline();
set_retry(0);
handle.block_on(async {
*self.last_lost_device.write().await =
Some(device_path.display().to_string());
*self.last_lost_reason.write().await = Some(e.to_string());
});
set_state(StreamerState::DeviceLost);
handle.block_on(async {
let streamer = Arc::clone(&self);
tokio::spawn(async move {
streamer.start_device_recovery_internal().await;
match classify_capture_io_error(&e) {
CaptureIoErrorKind::DeviceLost => {
error!("Video device lost: {} - {}", device_path.display(), e);
go_offline();
set_retry(0);
handle.block_on(async {
*self.last_lost_device.write().await =
Some(device_path.display().to_string());
*self.last_lost_reason.write().await = Some(e.to_string());
});
});
break 'capture;
}
if is_transient_signal_error {
if os_err == Some(71) {
warn!("Capture transient error (EPROTO/-71, often UVC USB): {}", e);
let is_uvc =
handle.block_on(async {
set_state(StreamerState::DeviceLost);
handle.block_on(async {
let streamer = Arc::clone(&self);
tokio::spawn(async move {
streamer.start_device_recovery_internal().await;
});
});
break 'capture;
}
CaptureIoErrorKind::TransientSignal { status } => {
if status == Some(crate::video::SignalStatus::UvcUsbError) {
warn!(
"Capture transient error (EPROTO/-71, often UVC USB): {}",
e
);
let is_uvc = handle.block_on(async {
self.current_device.read().await.as_ref().is_some_and(|d| {
d.driver.eq_ignore_ascii_case("uvcvideo")
})
});
if is_uvc {
go_offline();
set_state(StreamerState::UvcUsbError);
need_soft_restart = true;
break 'capture;
}
} else {
warn!(
if is_uvc {
go_offline();
set_state(StreamerState::UvcUsbError);
need_soft_restart = true;
break 'capture;
}
} else {
warn!(
"Capture transient error ({}): treating as NoSignal + soft-restart",
e
);
}
set_retry(
backoff_secs(no_signal_restart_count).saturating_mul(1000),
);
go_offline();
set_state(StreamerState::NoSignal);
need_soft_restart = true;
break 'capture;
}
set_retry(backoff_secs(no_signal_restart_count).saturating_mul(1000));
go_offline();
set_state(StreamerState::NoSignal);
need_soft_restart = true;
break 'capture;
CaptureIoErrorKind::Other => {}
}
let key = classify_capture_error(&e);
let key = capture_error_log_key(&e);
if capture_error_throttler.should_log(&key) {
let suppressed = suppressed_capture_errors.remove(&key).unwrap_or(0);
if suppressed > 0 {