use core::fmt;
use core::time::Duration;
use hdmi_hal::HdmiForumFrl;
use hdmi_hal::phy::{
EqParams, FrlOutput, FrlPhy, LanePatterns, PhyPower, TmdsPhy, TmdsPhyCapabilities,
TmdsPhyConfig,
};
use crate::bench::Core;
use crate::fault::Times;
use crate::line::{Line, RATIO_40_ABOVE_KHZ as LOW_RATE_KHZ};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PhySettings {
pub powered: bool,
pub configure_while_running: ConfigureWhileRunning,
pub scrambler_after_configure: ScramblerAfterConfigure,
pub start_latency: Duration,
}
impl PhySettings {
pub const DEFAULT: Self = Self {
powered: true,
configure_while_running: ConfigureWhileRunning::Fail,
scrambler_after_configure: ScramblerAfterConfigure::Opposite,
start_latency: Duration::from_millis(1),
};
#[must_use]
pub const fn with_powered(self, powered: bool) -> Self {
Self { powered, ..self }
}
#[must_use]
pub const fn with_configure_while_running(self, behaviour: ConfigureWhileRunning) -> Self {
Self {
configure_while_running: behaviour,
..self
}
}
#[must_use]
pub const fn with_scrambler_after_configure(self, behaviour: ScramblerAfterConfigure) -> Self {
Self {
scrambler_after_configure: behaviour,
..self
}
}
#[must_use]
pub const fn with_start_latency(self, latency: Duration) -> Self {
Self {
start_latency: latency,
..self
}
}
}
impl Default for PhySettings {
fn default() -> Self {
Self::DEFAULT
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConfigureWhileRunning {
Fail,
StopFirst,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScramblerAfterConfigure {
Opposite,
Keep,
Off,
FromRate,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PhyCall {
Configure(TmdsPhyConfig),
SetScrambling(bool),
StartOutput,
StopOutput,
PowerOn,
PowerOff,
SetFrlRate(HdmiForumFrl),
SendLtp(LanePatterns),
SetFrlOutput(FrlOutput),
AdjustEqualization(EqParams),
}
impl PhyCall {
pub fn kind(&self) -> PhyCallKind {
match self {
Self::Configure(_) => PhyCallKind::Configure,
Self::SetScrambling(_) => PhyCallKind::SetScrambling,
Self::StartOutput => PhyCallKind::StartOutput,
Self::StopOutput => PhyCallKind::StopOutput,
Self::PowerOn => PhyCallKind::PowerOn,
Self::PowerOff => PhyCallKind::PowerOff,
Self::SetFrlRate(_) => PhyCallKind::SetFrlRate,
Self::SendLtp(_) => PhyCallKind::SendLtp,
Self::SetFrlOutput(_) => PhyCallKind::SetFrlOutput,
Self::AdjustEqualization(_) => PhyCallKind::AdjustEqualization,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PhyCallKind {
Configure,
SetScrambling,
StartOutput,
StopOutput,
PowerOn,
PowerOff,
SetFrlRate,
SendLtp,
SetFrlOutput,
AdjustEqualization,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PhyErrorKind {
PoweredOff,
NotConfigured,
Running,
Unsupported,
NotInFrl,
Fault,
Coupled,
}
impl fmt::Display for PhyCallKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Configure => "configure",
Self::SetScrambling => "set_scrambling",
Self::StartOutput => "start_output",
Self::StopOutput => "stop_output",
Self::PowerOn => "power_on",
Self::PowerOff => "power_off",
Self::SetFrlRate => "set_frl_rate",
Self::SendLtp => "send_ltp",
Self::SetFrlOutput => "set_frl_output",
Self::AdjustEqualization => "adjust_equalization",
})
}
}
impl fmt::Display for PhyErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::PoweredOff => "the PHY is powered off",
Self::NotConfigured => "not configured since the last power-on",
Self::Running => "the output is running",
Self::Unsupported => "beyond the PHY's capabilities",
Self::NotInFrl => "not in FRL",
Self::Fault => "a scheduled fault",
Self::Coupled => "the coupled PHY's own error",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PhyError {
pub kind: PhyErrorKind,
pub call: PhyCall,
pub took_effect: bool,
}
impl fmt::Display for PhyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} failed: {}", self.call.kind(), self.kind)?;
if self.took_effect {
f.write_str(" (after it took effect)")?;
}
Ok(())
}
}
impl core::error::Error for PhyError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PhyFault {
pub call: Option<PhyCallKind>,
pub nth: u32,
pub times: Times,
pub took_effect: bool,
}
impl PhyFault {
pub const fn new() -> Self {
Self {
call: None,
nth: 1,
times: Times::Count(1),
took_effect: false,
}
}
#[must_use]
pub const fn on(self, kind: PhyCallKind) -> Self {
Self {
call: Some(kind),
..self
}
}
#[must_use]
pub const fn nth(self, n: u32) -> Self {
Self { nth: n, ..self }
}
#[must_use]
pub const fn times(self, times: Times) -> Self {
Self { times, ..self }
}
#[must_use]
pub const fn after_effect(self) -> Self {
Self {
took_effect: true,
..self
}
}
pub(crate) fn matches(&self, call: &PhyCall) -> bool {
self.call.is_none_or(|kind| kind == call.kind())
}
}
impl Default for PhyFault {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Mode {
None,
Tmds(TmdsPhyConfig),
Frl(FrlMode),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct FrlMode {
rate: HdmiForumFrl,
patterns: LanePatterns,
output: FrlOutput,
equalization: Option<EqParams>,
}
impl FrlMode {
pub(crate) fn new(rate: HdmiForumFrl) -> Self {
Self {
rate,
patterns: LanePatterns::default(),
output: FrlOutput::GapOnly,
equalization: None,
}
}
}
pub(crate) fn apply_frl(mode: &mut Mode, call: PhyCall) {
if let Mode::Frl(frl) = mode {
match call {
PhyCall::SendLtp(patterns) => frl.patterns = patterns,
PhyCall::SetFrlOutput(output) => frl.output = output,
PhyCall::AdjustEqualization(equalization) => frl.equalization = Some(equalization),
_ => {}
}
}
}
pub(crate) fn line_of(mode: Mode, running: bool, scrambler: bool) -> Line {
match mode {
Mode::Tmds(config) if running => Line::Tmds {
character_rate_khz: config.character_rate_khz,
ratio: config.clock_ratio,
scrambled: scrambler,
},
Mode::Frl(frl) => {
let line = Line::frl_with(frl.rate, frl.patterns, frl.output);
match frl.equalization {
Some(equalization) => line.with_equalization(equalization),
None => line,
}
}
_ => Line::Off,
}
}
#[derive(Debug)]
pub(crate) struct PhyState {
settings: PhySettings,
capabilities: TmdsPhyCapabilities,
powered: bool,
mode: Mode,
running: bool,
scrambler: bool,
}
impl PhyState {
pub(crate) fn new(settings: PhySettings, capabilities: TmdsPhyCapabilities) -> Self {
Self {
settings,
capabilities,
powered: settings.powered,
mode: Mode::None,
running: false,
scrambler: false,
}
}
pub(crate) fn capabilities(&self) -> TmdsPhyCapabilities {
self.capabilities
}
pub(crate) fn start_latency(&self) -> Duration {
self.settings.start_latency
}
pub(crate) fn line(&self) -> Line {
line_of(self.mode, self.running, self.scrambler)
}
pub(crate) fn is_running(&self) -> bool {
self.running
}
fn leave_modes(&mut self) {
self.mode = Mode::None;
self.running = false;
}
pub(crate) fn apply(&mut self, call: PhyCall) -> Result<(), PhyErrorKind> {
match call {
PhyCall::Configure(config) => {
if !self.powered {
return Err(PhyErrorKind::PoweredOff);
}
if config.character_rate_khz > self.capabilities.max_character_rate_khz {
return Err(PhyErrorKind::Unsupported);
}
if self.running
&& self.settings.configure_while_running == ConfigureWhileRunning::Fail
{
return Err(PhyErrorKind::Running);
}
let high_rate = config.character_rate_khz > LOW_RATE_KHZ;
let can = self.capabilities.scrambling
&& (high_rate || self.capabilities.scrambles_at_low_rate());
self.scrambler = can
&& match self.settings.scrambler_after_configure {
ScramblerAfterConfigure::Opposite => !high_rate,
ScramblerAfterConfigure::Keep => self.scrambler,
ScramblerAfterConfigure::Off => false,
ScramblerAfterConfigure::FromRate => high_rate,
};
self.mode = Mode::Tmds(config);
self.running = false;
Ok(())
}
PhyCall::SetScrambling(enabled) => {
if enabled {
if !self.capabilities.scrambling {
return Err(PhyErrorKind::Unsupported);
}
let low_rate = matches!(
self.mode,
Mode::Tmds(config) if config.character_rate_khz <= LOW_RATE_KHZ
);
if low_rate && !self.capabilities.scrambles_at_low_rate() {
return Err(PhyErrorKind::Unsupported);
}
}
self.scrambler = enabled;
Ok(())
}
PhyCall::StartOutput => {
if !self.powered {
return Err(PhyErrorKind::PoweredOff);
}
if !matches!(self.mode, Mode::Tmds(_)) {
return Err(PhyErrorKind::NotConfigured);
}
self.running = true;
Ok(())
}
PhyCall::StopOutput => {
self.running = false;
if matches!(self.mode, Mode::Frl(_)) {
self.mode = Mode::None;
}
Ok(())
}
PhyCall::PowerOn => {
if !self.powered {
self.powered = true;
self.leave_modes();
}
Ok(())
}
PhyCall::PowerOff => {
self.powered = false;
self.leave_modes();
Ok(())
}
PhyCall::SetFrlRate(rate) => {
if !self.powered {
return Err(PhyErrorKind::PoweredOff);
}
if rate == HdmiForumFrl::NotSupported {
if matches!(self.mode, Mode::Frl(_)) {
self.mode = Mode::None;
}
} else {
self.running = false;
self.mode = Mode::Frl(FrlMode::new(rate));
}
Ok(())
}
PhyCall::SendLtp(_) | PhyCall::SetFrlOutput(_) | PhyCall::AdjustEqualization(_) => {
if !self.powered {
Err(PhyErrorKind::PoweredOff)
} else if !matches!(self.mode, Mode::Frl(_)) {
Err(PhyErrorKind::NotInFrl)
} else {
apply_frl(&mut self.mode, call);
Ok(())
}
}
}
}
}
#[derive(Clone, Copy)]
pub struct Phy<'b> {
core: &'b (dyn Core + Sync + 'b),
}
impl<'b> Phy<'b> {
pub(crate) fn new(core: &'b (dyn Core + Sync + 'b)) -> Self {
Self { core }
}
fn call(&self, call: PhyCall) -> Result<(), PhyError> {
self.core.spend();
let (result, took_effect) = self.core.phy_call(call);
result.map_err(|kind| PhyError {
kind,
call,
took_effect,
})
}
}
impl fmt::Debug for Phy<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Phy")
.field("capabilities", &self.core.phy_capabilities())
.finish_non_exhaustive()
}
}
impl TmdsPhy for Phy<'_> {
type Error = PhyError;
fn capabilities(&self) -> TmdsPhyCapabilities {
self.core.phy_capabilities()
}
fn configure(&mut self, config: TmdsPhyConfig) -> Result<(), PhyError> {
self.call(PhyCall::Configure(config))
}
fn set_scrambling(&mut self, enabled: bool) -> Result<(), PhyError> {
self.call(PhyCall::SetScrambling(enabled))
}
fn start_output(&mut self) -> Result<(), PhyError> {
self.call(PhyCall::StartOutput)
}
fn stop_output(&mut self) -> Result<(), PhyError> {
self.call(PhyCall::StopOutput)
}
}
impl PhyPower for Phy<'_> {
type Error = PhyError;
fn power_on(&mut self) -> Result<(), PhyError> {
self.call(PhyCall::PowerOn)
}
fn power_off(&mut self) -> Result<(), PhyError> {
self.call(PhyCall::PowerOff)
}
}
impl FrlPhy for Phy<'_> {
type Error = PhyError;
fn set_frl_rate(&mut self, rate: HdmiForumFrl) -> Result<(), PhyError> {
self.call(PhyCall::SetFrlRate(rate))
}
fn send_ltp(&mut self, patterns: LanePatterns) -> Result<(), PhyError> {
self.call(PhyCall::SendLtp(patterns))
}
fn set_frl_output(&mut self, output: FrlOutput) -> Result<(), PhyError> {
self.call(PhyCall::SetFrlOutput(output))
}
fn adjust_equalization(&mut self, params: EqParams) -> Result<(), PhyError> {
self.call(PhyCall::AdjustEqualization(params))
}
}