1use core::fmt;
9use core::time::Duration;
10
11use hdmi_hal::ddc::{DdcError, DdcErrorKind};
12use hdmi_hal::time::Timestamp;
13
14use crate::error::UpdateError;
15use crate::event::{CancelPoint, TmdsStep};
16use crate::params::TmdsLinkParams;
17use crate::types::TmdsConfigReading;
18
19#[non_exhaustive]
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum BringUpOutcome<S, P> {
23 Up(LinkUp<S>),
25 #[non_exhaustive]
27 Cancelled {
28 at: CancelPoint,
30 cleanup: Cleanup<S, P>,
33 warnings: Warnings<S>,
35 },
36}
37
38#[non_exhaustive]
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct LinkUp<S> {
43 pub link: TmdsLinkParams,
45 pub sink_written_at: Option<Timestamp>,
49 pub output_started_at: Timestamp,
51 pub check: ScramblingCheck<S>,
55 pub warnings: Warnings<S>,
57}
58
59#[non_exhaustive]
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum BringUpWarning<S> {
63 FrlRateClearFailed(S),
65 FltUpdateClearFailed(UpdateError<S>),
67 SinkVersionReadFailed(S),
69 SourceVersionWriteFailed(S),
71 #[non_exhaustive]
73 TmdsConfigWriteFailed {
74 error: UpdateError<S>,
77 read_back: Option<Result<TmdsConfigReading, S>>,
81 },
82 #[non_exhaustive]
85 DeadlineMissed {
86 by: Duration,
88 },
89 #[non_exhaustive]
92 ScramblingNotConfirmed {
93 result: CheckResult,
95 },
96}
97
98const WARNING_KINDS: usize = 7;
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub struct Warnings<S> {
105 list: [Option<BringUpWarning<S>>; WARNING_KINDS],
106 len: usize,
107}
108
109impl<S> Warnings<S> {
110 pub(crate) const fn new() -> Self {
112 Self {
113 list: [None, None, None, None, None, None, None],
114 len: 0,
115 }
116 }
117
118 pub(crate) fn push(&mut self, warning: BringUpWarning<S>) {
120 if let Some(slot) = self.list.get_mut(self.len) {
121 *slot = Some(warning);
122 self.len += 1;
123 }
124 }
125
126 pub fn iter_warnings(&self) -> impl Iterator<Item = &BringUpWarning<S>> {
128 self.list[..self.len].iter().flatten()
129 }
130
131 #[must_use]
133 pub const fn len(&self) -> usize {
134 self.len
135 }
136
137 #[must_use]
139 pub const fn is_empty(&self) -> bool {
140 self.len == 0
141 }
142}
143
144#[non_exhaustive]
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum BringUpError<S, P> {
148 #[non_exhaustive]
152 Scdc {
153 step: TmdsStep,
155 error: S,
157 output: OutputState,
159 cleanup: Cleanup<S, P>,
161 warnings: Warnings<S>,
163 },
164 #[non_exhaustive]
166 Phy {
167 step: TmdsStep,
169 error: P,
171 output: OutputState,
173 cleanup: Cleanup<S, P>,
175 warnings: Warnings<S>,
177 },
178 #[non_exhaustive]
182 VideoMismatch {
183 link_rate_khz: u32,
185 video_rate_khz: Option<u32>,
188 },
189}
190
191#[non_exhaustive]
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub enum Cleanup<S, P> {
195 TornDown(Result<TornDown<S>, TearDownError<S, P>>),
198 Skipped,
201}
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
205pub enum OutputState {
206 Stopped,
208 MayBeRunning,
210}
211
212#[non_exhaustive]
214#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub struct ScramblingCheck<S> {
216 pub result: CheckResult,
218 pub reads: u32,
220 pub failed_reads: u32,
222 pub first_error: Option<FailedRead<S>>,
224 pub set_after: Option<Duration>,
228 pub read_cap_reached: bool,
231}
232
233impl<S> ScramblingCheck<S> {
234 pub(crate) const NOT_APPLICABLE: Self = Self {
236 result: CheckResult::NotApplicable,
237 reads: 0,
238 failed_reads: 0,
239 first_error: None,
240 set_after: None,
241 read_cap_reached: false,
242 };
243}
244
245impl<S: DdcError> ScramblingCheck<S> {
246 #[must_use]
249 pub fn kinds(&self) -> ScramblingCheck<DdcErrorKind> {
250 ScramblingCheck {
251 result: self.result,
252 reads: self.reads,
253 failed_reads: self.failed_reads,
254 first_error: self.first_error.as_ref().map(|f| FailedRead {
255 error: f.error.kind(),
256 after: f.after,
257 }),
258 set_after: self.set_after,
259 read_cap_reached: self.read_cap_reached,
260 }
261 }
262}
263
264#[non_exhaustive]
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
267pub enum CheckResult {
268 NotApplicable,
270 Set,
272 NotSet,
274 Unreadable,
277 Cancelled,
279}
280
281#[non_exhaustive]
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub struct FailedRead<S> {
285 pub error: S,
287 pub after: Duration,
289}
290
291#[non_exhaustive]
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub enum SinkClear<S> {
295 NotRequested,
297 NothingToClear,
299 SkippedSinkGone,
301 Cleared,
303 Failed(S),
305}
306
307impl<S: DdcError> SinkClear<S> {
308 #[must_use]
310 pub fn kinds(&self) -> SinkClear<DdcErrorKind> {
311 match self {
312 Self::NotRequested => SinkClear::NotRequested,
313 Self::NothingToClear => SinkClear::NothingToClear,
314 Self::SkippedSinkGone => SinkClear::SkippedSinkGone,
315 Self::Cleared => SinkClear::Cleared,
316 Self::Failed(e) => SinkClear::Failed(e.kind()),
317 }
318 }
319}
320
321#[non_exhaustive]
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324pub enum ReconnectCheck<S> {
325 Matches,
327 #[non_exhaustive]
330 Lost {
331 read: TmdsConfigReading,
333 },
334 Unreadable(S),
336 NotApplicable,
340 SinkChanged,
343}
344
345impl<S: DdcError> ReconnectCheck<S> {
346 #[must_use]
348 pub fn kinds(&self) -> ReconnectCheck<DdcErrorKind> {
349 match self {
350 Self::Matches => ReconnectCheck::Matches,
351 Self::Lost { read } => ReconnectCheck::Lost { read: *read },
352 Self::Unreadable(e) => ReconnectCheck::Unreadable(e.kind()),
353 Self::NotApplicable => ReconnectCheck::NotApplicable,
354 Self::SinkChanged => ReconnectCheck::SinkChanged,
355 }
356 }
357}
358
359#[non_exhaustive]
361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362pub struct Restored<S> {
363 pub sink_written_at: Option<Timestamp>,
366 pub check: ScramblingCheck<S>,
370 pub write_failed: Option<UpdateError<S>>,
374}
375
376#[non_exhaustive]
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub enum RestoreError<S, P> {
380 Scdc(UpdateError<S>),
383 #[non_exhaustive]
385 Phy {
386 error: P,
388 sink_written_at: Option<Timestamp>,
391 write_failed: Option<UpdateError<S>>,
393 },
394}
395
396#[non_exhaustive]
398#[derive(Debug, Clone, Copy, PartialEq, Eq)]
399pub struct TornDown<S> {
400 pub sink: SinkClear<S>,
402}
403
404#[non_exhaustive]
408#[derive(Debug, Clone, Copy, PartialEq, Eq)]
409pub struct TearDownError<S, P> {
410 pub sink: SinkClear<S>,
412 pub scrambler: Option<P>,
414 pub output: Option<P>,
416}
417
418impl<S: fmt::Display, P: fmt::Debug> fmt::Display for BringUpError<S, P> {
419 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420 match self {
421 Self::Scdc { step, error, .. } => {
422 write!(f, "bring-up stopped at {step:?}: SCDC error: {error}")
423 }
424 Self::Phy { step, error, .. } => {
425 write!(f, "bring-up stopped at {step:?}: PHY error: {error:?}")
426 }
427 Self::VideoMismatch {
428 link_rate_khz,
429 video_rate_khz: Some(video),
430 } => write!(
431 f,
432 "bring-up refused: the link is for {link_rate_khz} kHz, the video gives {video} kHz"
433 ),
434 Self::VideoMismatch { link_rate_khz, .. } => write!(
435 f,
436 "bring-up refused: the link is for {link_rate_khz} kHz, and TMDS cannot carry the video"
437 ),
438 }
439 }
440}
441
442impl<S: core::error::Error + 'static, P: fmt::Debug> core::error::Error for BringUpError<S, P> {
444 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
445 match self {
446 Self::Scdc { error, .. } => Some(error),
447 Self::Phy { .. } | Self::VideoMismatch { .. } => None,
448 }
449 }
450}
451
452impl<S, P: fmt::Debug> fmt::Display for TearDownError<S, P> {
453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454 f.write_str("tear-down: ")?;
455 match (&self.scrambler, &self.output) {
456 (Some(s), Some(o)) => write!(
457 f,
458 "turning the scrambler off failed: {s:?}; stopping the output failed: {o:?}"
459 ),
460 (Some(s), None) => write!(f, "turning the scrambler off failed: {s:?}"),
461 (None, Some(o)) => write!(f, "stopping the output failed: {o:?}"),
462 (None, None) => f.write_str("a PHY step failed"),
463 }
464 }
465}
466
467impl<S: fmt::Debug, P: fmt::Debug> core::error::Error for TearDownError<S, P> {}
469
470impl<S: fmt::Display, P: fmt::Debug> fmt::Display for RestoreError<S, P> {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 match self {
473 Self::Scdc(error) => write!(f, "quick restore stopped at the sink's write: {error}"),
474 Self::Phy { error, .. } => {
475 write!(f, "quick restore: setting the scrambler failed: {error:?}")
476 }
477 }
478 }
479}
480
481impl<S: core::error::Error + 'static, P: fmt::Debug> core::error::Error for RestoreError<S, P> {
483 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
484 match self {
485 Self::Scdc(error) => Some(error),
486 Self::Phy { .. } => None,
487 }
488 }
489}
490
491#[cfg(test)]
492mod tests {
493 use super::*;
494
495 #[derive(Debug, Clone, Copy, PartialEq)]
496 struct Bus;
497
498 impl fmt::Display for Bus {
499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
500 f.write_str("bus gone")
501 }
502 }
503
504 impl core::error::Error for Bus {}
505
506 #[test]
507 fn errors_print_and_chain() {
508 extern crate std;
509 use core::error::Error;
510 use std::string::ToString;
511
512 let scdc = BringUpError::<Bus, ()>::Scdc {
513 step: TmdsStep::WriteTmdsConfig,
514 error: Bus,
515 output: OutputState::Stopped,
516 cleanup: Cleanup::Skipped,
517 warnings: Warnings::new(),
518 };
519 assert_eq!(
520 scdc.to_string(),
521 "bring-up stopped at WriteTmdsConfig: SCDC error: bus gone"
522 );
523 assert_eq!(scdc.source().unwrap().to_string(), "bus gone");
524 let phy = BringUpError::<Bus, ()>::Phy {
525 step: TmdsStep::StartOutput,
526 error: (),
527 output: OutputState::MayBeRunning,
528 cleanup: Cleanup::Skipped,
529 warnings: Warnings::new(),
530 };
531 assert_eq!(
532 phy.to_string(),
533 "bring-up stopped at StartOutput: PHY error: ()"
534 );
535 assert!(phy.source().is_none());
536 let mismatch = |video_rate_khz| BringUpError::<Bus, ()>::VideoMismatch {
537 link_rate_khz: 594_000,
538 video_rate_khz,
539 };
540 assert_eq!(
541 mismatch(Some(148_500)).to_string(),
542 "bring-up refused: the link is for 594000 kHz, the video gives 148500 kHz"
543 );
544 assert_eq!(
545 mismatch(None).to_string(),
546 "bring-up refused: the link is for 594000 kHz, and TMDS cannot carry the video"
547 );
548 assert!(mismatch(None).source().is_none());
549
550 let torn = |scrambler, output| TearDownError::<Bus, ()> {
551 sink: SinkClear::NotRequested,
552 scrambler,
553 output,
554 };
555 assert_eq!(
556 torn(Some(()), Some(())).to_string(),
557 "tear-down: turning the scrambler off failed: (); stopping the output failed: ()"
558 );
559 assert_eq!(
560 torn(Some(()), None).to_string(),
561 "tear-down: turning the scrambler off failed: ()"
562 );
563 assert_eq!(
564 torn(None, Some(())).to_string(),
565 "tear-down: stopping the output failed: ()"
566 );
567 assert_eq!(torn(None, None).to_string(), "tear-down: a PHY step failed");
568 assert!(torn(None, Some(())).source().is_none());
569
570 let restore = RestoreError::<Bus, ()>::Scdc(UpdateError::Read(Bus));
571 assert_eq!(
572 restore.to_string(),
573 "quick restore stopped at the sink's write: read failed, nothing written: bus gone"
574 );
575 assert!(restore.source().is_some());
576 let restore = RestoreError::<Bus, ()>::Phy {
577 error: (),
578 sink_written_at: None,
579 write_failed: None,
580 };
581 assert_eq!(
582 restore.to_string(),
583 "quick restore: setting the scrambler failed: ()"
584 );
585 assert!(restore.source().is_none());
586 }
587
588 #[test]
589 fn warnings_keep_the_order_and_never_overflow() {
590 let mut w = Warnings::<DdcErrorKind>::new();
591 assert!(w.is_empty());
592 w.push(BringUpWarning::SourceVersionWriteFailed(DdcErrorKind::Busy));
593 w.push(BringUpWarning::DeadlineMissed {
594 by: Duration::from_millis(3),
595 });
596 assert_eq!(w.len(), 2);
597 assert!(!w.is_empty());
598 let mut it = w.iter_warnings();
599 assert_eq!(
600 it.next(),
601 Some(&BringUpWarning::SourceVersionWriteFailed(
602 DdcErrorKind::Busy
603 ))
604 );
605 assert!(matches!(
606 it.next(),
607 Some(BringUpWarning::DeadlineMissed { .. })
608 ));
609 assert_eq!(it.next(), None);
610 drop(it);
611 for _ in 0..6 {
614 w.push(BringUpWarning::FrlRateClearFailed(DdcErrorKind::Other));
615 }
616 assert_eq!(w.len(), WARNING_KINDS);
617 }
618
619 #[test]
620 fn a_plain_links_check_read_nothing() {
621 let check = ScramblingCheck::<DdcErrorKind>::NOT_APPLICABLE;
622 assert_eq!(check.result, CheckResult::NotApplicable);
623 assert_eq!((check.reads, check.failed_reads), (0, 0));
624 assert!(check.first_error.is_none() && check.set_after.is_none());
625 assert!(!check.read_cap_reached);
626 }
627
628 #[test]
629 fn reconnect_kinds_keep_the_result_and_drop_the_value() {
630 let read = TmdsConfigReading::new(crate::types::SinkTmdsConfig::new(false, false), 0x80);
631 assert_eq!(
632 ReconnectCheck::<DdcErrorKind>::Unreadable(DdcErrorKind::Detached).kinds(),
633 ReconnectCheck::Unreadable(DdcErrorKind::Detached)
634 );
635 for check in [
636 ReconnectCheck::<DdcErrorKind>::Matches,
637 ReconnectCheck::Lost { read },
638 ReconnectCheck::NotApplicable,
639 ReconnectCheck::SinkChanged,
640 ] {
641 assert_eq!(check.kinds(), check);
642 }
643 }
644
645 #[test]
646 fn kinds_keeps_the_result_and_drops_the_value() {
647 assert_eq!(
648 SinkClear::<DdcErrorKind>::Failed(DdcErrorKind::Busy).kinds(),
649 SinkClear::Failed(DdcErrorKind::Busy)
650 );
651 for clear in [
652 SinkClear::<DdcErrorKind>::NotRequested,
653 SinkClear::NothingToClear,
654 SinkClear::SkippedSinkGone,
655 SinkClear::Cleared,
656 ] {
657 assert_eq!(clear.kinds(), clear);
658 }
659 }
660}