use core::fmt;
use core::time::Duration;
use hdmi_hal::ddc::{DdcError, DdcErrorKind};
use hdmi_hal::time::Timestamp;
use crate::error::UpdateError;
use crate::event::{CancelPoint, TmdsStep};
use crate::params::TmdsLinkParams;
use crate::types::TmdsConfigReading;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BringUpOutcome<S, P> {
Up(LinkUp<S>),
#[non_exhaustive]
Cancelled {
at: CancelPoint,
cleanup: Cleanup<S, P>,
warnings: Warnings<S>,
},
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinkUp<S> {
pub link: TmdsLinkParams,
pub sink_written_at: Option<Timestamp>,
pub output_started_at: Timestamp,
pub check: ScramblingCheck<S>,
pub warnings: Warnings<S>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BringUpWarning<S> {
FrlRateClearFailed(S),
FltUpdateClearFailed(UpdateError<S>),
SinkVersionReadFailed(S),
SourceVersionWriteFailed(S),
#[non_exhaustive]
TmdsConfigWriteFailed {
error: UpdateError<S>,
read_back: Option<Result<TmdsConfigReading, S>>,
},
#[non_exhaustive]
DeadlineMissed {
by: Duration,
},
#[non_exhaustive]
ScramblingNotConfirmed {
result: CheckResult,
},
}
const WARNING_KINDS: usize = 7;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Warnings<S> {
list: [Option<BringUpWarning<S>>; WARNING_KINDS],
len: usize,
}
impl<S> Warnings<S> {
pub(crate) const fn new() -> Self {
Self {
list: [None, None, None, None, None, None, None],
len: 0,
}
}
pub(crate) fn push(&mut self, warning: BringUpWarning<S>) {
if let Some(slot) = self.list.get_mut(self.len) {
*slot = Some(warning);
self.len += 1;
}
}
pub fn iter_warnings(&self) -> impl Iterator<Item = &BringUpWarning<S>> {
self.list[..self.len].iter().flatten()
}
#[must_use]
pub const fn len(&self) -> usize {
self.len
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BringUpError<S, P> {
#[non_exhaustive]
Scdc {
step: TmdsStep,
error: S,
output: OutputState,
cleanup: Cleanup<S, P>,
warnings: Warnings<S>,
},
#[non_exhaustive]
Phy {
step: TmdsStep,
error: P,
output: OutputState,
cleanup: Cleanup<S, P>,
warnings: Warnings<S>,
},
#[non_exhaustive]
VideoMismatch {
link_rate_khz: u32,
video_rate_khz: Option<u32>,
},
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cleanup<S, P> {
TornDown(Result<TornDown<S>, TearDownError<S, P>>),
Skipped,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OutputState {
Stopped,
MayBeRunning,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ScramblingCheck<S> {
pub result: CheckResult,
pub reads: u32,
pub failed_reads: u32,
pub first_error: Option<FailedRead<S>>,
pub set_after: Option<Duration>,
pub read_cap_reached: bool,
}
impl<S> ScramblingCheck<S> {
pub(crate) const NOT_APPLICABLE: Self = Self {
result: CheckResult::NotApplicable,
reads: 0,
failed_reads: 0,
first_error: None,
set_after: None,
read_cap_reached: false,
};
}
impl<S: DdcError> ScramblingCheck<S> {
#[must_use]
pub fn kinds(&self) -> ScramblingCheck<DdcErrorKind> {
ScramblingCheck {
result: self.result,
reads: self.reads,
failed_reads: self.failed_reads,
first_error: self.first_error.as_ref().map(|f| FailedRead {
error: f.error.kind(),
after: f.after,
}),
set_after: self.set_after,
read_cap_reached: self.read_cap_reached,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CheckResult {
NotApplicable,
Set,
NotSet,
Unreadable,
Cancelled,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FailedRead<S> {
pub error: S,
pub after: Duration,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SinkClear<S> {
NotRequested,
NothingToClear,
SkippedSinkGone,
Cleared,
Failed(S),
}
impl<S: DdcError> SinkClear<S> {
#[must_use]
pub fn kinds(&self) -> SinkClear<DdcErrorKind> {
match self {
Self::NotRequested => SinkClear::NotRequested,
Self::NothingToClear => SinkClear::NothingToClear,
Self::SkippedSinkGone => SinkClear::SkippedSinkGone,
Self::Cleared => SinkClear::Cleared,
Self::Failed(e) => SinkClear::Failed(e.kind()),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReconnectCheck<S> {
Matches,
#[non_exhaustive]
Lost {
read: TmdsConfigReading,
},
Unreadable(S),
NotApplicable,
SinkChanged,
}
impl<S: DdcError> ReconnectCheck<S> {
#[must_use]
pub fn kinds(&self) -> ReconnectCheck<DdcErrorKind> {
match self {
Self::Matches => ReconnectCheck::Matches,
Self::Lost { read } => ReconnectCheck::Lost { read: *read },
Self::Unreadable(e) => ReconnectCheck::Unreadable(e.kind()),
Self::NotApplicable => ReconnectCheck::NotApplicable,
Self::SinkChanged => ReconnectCheck::SinkChanged,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Restored<S> {
pub sink_written_at: Option<Timestamp>,
pub check: ScramblingCheck<S>,
pub write_failed: Option<UpdateError<S>>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RestoreError<S, P> {
Scdc(UpdateError<S>),
#[non_exhaustive]
Phy {
error: P,
sink_written_at: Option<Timestamp>,
write_failed: Option<UpdateError<S>>,
},
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TornDown<S> {
pub sink: SinkClear<S>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TearDownError<S, P> {
pub sink: SinkClear<S>,
pub scrambler: Option<P>,
pub output: Option<P>,
}
impl<S: fmt::Display, P: fmt::Debug> fmt::Display for BringUpError<S, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Scdc { step, error, .. } => {
write!(f, "bring-up stopped at {step:?}: SCDC error: {error}")
}
Self::Phy { step, error, .. } => {
write!(f, "bring-up stopped at {step:?}: PHY error: {error:?}")
}
Self::VideoMismatch {
link_rate_khz,
video_rate_khz: Some(video),
} => write!(
f,
"bring-up refused: the link is for {link_rate_khz} kHz, the video gives {video} kHz"
),
Self::VideoMismatch { link_rate_khz, .. } => write!(
f,
"bring-up refused: the link is for {link_rate_khz} kHz, and TMDS cannot carry the video"
),
}
}
}
impl<S: core::error::Error + 'static, P: fmt::Debug> core::error::Error for BringUpError<S, P> {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Scdc { error, .. } => Some(error),
Self::Phy { .. } | Self::VideoMismatch { .. } => None,
}
}
}
impl<S, P: fmt::Debug> fmt::Display for TearDownError<S, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("tear-down: ")?;
match (&self.scrambler, &self.output) {
(Some(s), Some(o)) => write!(
f,
"turning the scrambler off failed: {s:?}; stopping the output failed: {o:?}"
),
(Some(s), None) => write!(f, "turning the scrambler off failed: {s:?}"),
(None, Some(o)) => write!(f, "stopping the output failed: {o:?}"),
(None, None) => f.write_str("a PHY step failed"),
}
}
}
impl<S: fmt::Debug, P: fmt::Debug> core::error::Error for TearDownError<S, P> {}
impl<S: fmt::Display, P: fmt::Debug> fmt::Display for RestoreError<S, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Scdc(error) => write!(f, "quick restore stopped at the sink's write: {error}"),
Self::Phy { error, .. } => {
write!(f, "quick restore: setting the scrambler failed: {error:?}")
}
}
}
}
impl<S: core::error::Error + 'static, P: fmt::Debug> core::error::Error for RestoreError<S, P> {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Scdc(error) => Some(error),
Self::Phy { .. } => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Bus;
impl fmt::Display for Bus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("bus gone")
}
}
impl core::error::Error for Bus {}
#[test]
fn errors_print_and_chain() {
extern crate std;
use core::error::Error;
use std::string::ToString;
let scdc = BringUpError::<Bus, ()>::Scdc {
step: TmdsStep::WriteTmdsConfig,
error: Bus,
output: OutputState::Stopped,
cleanup: Cleanup::Skipped,
warnings: Warnings::new(),
};
assert_eq!(
scdc.to_string(),
"bring-up stopped at WriteTmdsConfig: SCDC error: bus gone"
);
assert_eq!(scdc.source().unwrap().to_string(), "bus gone");
let phy = BringUpError::<Bus, ()>::Phy {
step: TmdsStep::StartOutput,
error: (),
output: OutputState::MayBeRunning,
cleanup: Cleanup::Skipped,
warnings: Warnings::new(),
};
assert_eq!(
phy.to_string(),
"bring-up stopped at StartOutput: PHY error: ()"
);
assert!(phy.source().is_none());
let mismatch = |video_rate_khz| BringUpError::<Bus, ()>::VideoMismatch {
link_rate_khz: 594_000,
video_rate_khz,
};
assert_eq!(
mismatch(Some(148_500)).to_string(),
"bring-up refused: the link is for 594000 kHz, the video gives 148500 kHz"
);
assert_eq!(
mismatch(None).to_string(),
"bring-up refused: the link is for 594000 kHz, and TMDS cannot carry the video"
);
assert!(mismatch(None).source().is_none());
let torn = |scrambler, output| TearDownError::<Bus, ()> {
sink: SinkClear::NotRequested,
scrambler,
output,
};
assert_eq!(
torn(Some(()), Some(())).to_string(),
"tear-down: turning the scrambler off failed: (); stopping the output failed: ()"
);
assert_eq!(
torn(Some(()), None).to_string(),
"tear-down: turning the scrambler off failed: ()"
);
assert_eq!(
torn(None, Some(())).to_string(),
"tear-down: stopping the output failed: ()"
);
assert_eq!(torn(None, None).to_string(), "tear-down: a PHY step failed");
assert!(torn(None, Some(())).source().is_none());
let restore = RestoreError::<Bus, ()>::Scdc(UpdateError::Read(Bus));
assert_eq!(
restore.to_string(),
"quick restore stopped at the sink's write: read failed, nothing written: bus gone"
);
assert!(restore.source().is_some());
let restore = RestoreError::<Bus, ()>::Phy {
error: (),
sink_written_at: None,
write_failed: None,
};
assert_eq!(
restore.to_string(),
"quick restore: setting the scrambler failed: ()"
);
assert!(restore.source().is_none());
}
#[test]
fn warnings_keep_the_order_and_never_overflow() {
let mut w = Warnings::<DdcErrorKind>::new();
assert!(w.is_empty());
w.push(BringUpWarning::SourceVersionWriteFailed(DdcErrorKind::Busy));
w.push(BringUpWarning::DeadlineMissed {
by: Duration::from_millis(3),
});
assert_eq!(w.len(), 2);
assert!(!w.is_empty());
let mut it = w.iter_warnings();
assert_eq!(
it.next(),
Some(&BringUpWarning::SourceVersionWriteFailed(
DdcErrorKind::Busy
))
);
assert!(matches!(
it.next(),
Some(BringUpWarning::DeadlineMissed { .. })
));
assert_eq!(it.next(), None);
drop(it);
for _ in 0..6 {
w.push(BringUpWarning::FrlRateClearFailed(DdcErrorKind::Other));
}
assert_eq!(w.len(), WARNING_KINDS);
}
#[test]
fn a_plain_links_check_read_nothing() {
let check = ScramblingCheck::<DdcErrorKind>::NOT_APPLICABLE;
assert_eq!(check.result, CheckResult::NotApplicable);
assert_eq!((check.reads, check.failed_reads), (0, 0));
assert!(check.first_error.is_none() && check.set_after.is_none());
assert!(!check.read_cap_reached);
}
#[test]
fn reconnect_kinds_keep_the_result_and_drop_the_value() {
let read = TmdsConfigReading::new(crate::types::SinkTmdsConfig::new(false, false), 0x80);
assert_eq!(
ReconnectCheck::<DdcErrorKind>::Unreadable(DdcErrorKind::Detached).kinds(),
ReconnectCheck::Unreadable(DdcErrorKind::Detached)
);
for check in [
ReconnectCheck::<DdcErrorKind>::Matches,
ReconnectCheck::Lost { read },
ReconnectCheck::NotApplicable,
ReconnectCheck::SinkChanged,
] {
assert_eq!(check.kinds(), check);
}
}
#[test]
fn kinds_keeps_the_result_and_drops_the_value() {
assert_eq!(
SinkClear::<DdcErrorKind>::Failed(DdcErrorKind::Busy).kinds(),
SinkClear::Failed(DdcErrorKind::Busy)
);
for clear in [
SinkClear::<DdcErrorKind>::NotRequested,
SinkClear::NothingToClear,
SinkClear::SkippedSinkGone,
SinkClear::Cleared,
] {
assert_eq!(clear.kinds(), clear);
}
}
}