Skip to main content

hdmi_hal/phy/
mod.rs

1use display_types::cea861::hdmi_forum::HdmiForumFrl;
2
3/// The colour depth and format [`TmdsVideo`] carries, re-exported from `display-types` so
4/// that implementations name the same types hdmi-hal does, with no direct dependency.
5pub use display_types::{ColorBitDepth, ColorFormat};
6
7/// A link training pattern to be driven on the physical lanes.
8///
9/// Produced by the link training state machine and passed to [`FrlPhy::send_ltp`].
10/// The discriminants are the pattern values a sink requests in the SCDC Status_Flags
11/// LTP fields. Request values that are not patterns (0 for no pattern, and the TxFFE
12/// and rate change requests) are handled by the link training layer and have no variant.
13#[non_exhaustive]
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[repr(u8)]
16pub enum LtpPattern {
17    /// All ones.
18    AllOnes = 1,
19    /// All zeros.
20    AllZeros = 2,
21    /// Nyquist clock pattern.
22    NyquistClock = 3,
23    /// DDE (Data Dependent Equalization) compliance pattern.
24    DdeCompliance = 4,
25    /// LFSR pattern 0.
26    Lfsr0 = 5,
27    /// LFSR pattern 1.
28    Lfsr1 = 6,
29    /// LFSR pattern 2.
30    Lfsr2 = 7,
31    /// LFSR pattern 3.
32    Lfsr3 = 8,
33}
34
35impl LtpPattern {
36    /// Returns the pattern's SCDC value (1–8).
37    pub const fn value(self) -> u8 {
38        self as u8
39    }
40}
41
42/// The link training pattern for each lane, passed to [`FrlPhy::send_ltp`].
43///
44/// Always the full per-lane set: the PHY applies it as given, and the link training
45/// layer tracks which pattern each lane carries. `None` means no training pattern on
46/// that lane; `None` on every lane stops the training patterns. `lane3` is `None` in
47/// 3-lane FRL mode.
48#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
49pub struct LanePatterns {
50    /// Pattern for lane 0.
51    pub lane0: Option<LtpPattern>,
52    /// Pattern for lane 1.
53    pub lane1: Option<LtpPattern>,
54    /// Pattern for lane 2.
55    pub lane2: Option<LtpPattern>,
56    /// Pattern for lane 3. `None` in 3-lane FRL mode.
57    pub lane3: Option<LtpPattern>,
58}
59
60/// What the transmitter sends on the FRL lanes once training patterns are stopped.
61///
62/// Passed to [`FrlPhy::set_frl_output`].
63///
64/// Deliberately exhaustive, unlike [`LtpPattern`]. The two variants are the two states of
65/// an FRL link, training and carrying content, not a list that grows with each HDMI
66/// version. A PHY has to implement both, and has no sensible behaviour for a mode it does
67/// not know: a wildcard arm could only fail. If a later HDMI version adds a mode, it should
68/// reach every implementation as a compile error in a breaking release, not as a runtime
69/// error from a PHY that was never updated.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub enum FrlOutput {
72    /// Gap characters only, with no video, data islands or control periods. Used during
73    /// link training and while waiting for the sink to start FRL.
74    GapOnly,
75    /// Video, data islands and control periods. Set by the caller once link training
76    /// has succeeded.
77    Active,
78}
79
80/// A TxFFE (transmitter feed-forward equalization) level index, 0–7.
81///
82/// The level a lane's transmitter applies during FRL training. The range is checked on
83/// construction; the lower per-rate limit the source advertises to the sink is the link
84/// training layer's concern.
85#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
86pub struct TxFfeLevel(u8);
87
88impl TxFfeLevel {
89    /// The highest TxFFE level, 7.
90    pub const MAX: Self = Self(7);
91
92    /// Returns the level for `level`, or `None` if it is above 7.
93    pub const fn new(level: u8) -> Option<Self> {
94        if level <= Self::MAX.0 {
95            Some(Self(level))
96        } else {
97            None
98        }
99    }
100
101    /// Returns the level index (0–7).
102    pub const fn value(self) -> u8 {
103        self.0
104    }
105}
106
107/// Per-lane equalization parameters carried by [`EqParams`].
108#[non_exhaustive]
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
110pub struct LaneEqParams {
111    /// TxFFE level for the lane. Defaults to 0.
112    pub tx_ffe_level: TxFfeLevel,
113}
114
115/// Restrictions on the TxFFE components, as a compliance tester sets them.
116///
117/// TxFFE combines two components: pre-shoot (pre-cursor) and de-emphasis (post-cursor).
118/// The sink's `Source_Test_Configuration` register (SCDC 0x35, bits 1–3) can restrict them,
119/// and the three bits are carried here exactly as written, for the whole link. Each bit's
120/// plain meaning:
121///
122/// - `pre_shoot_only` (`TxFFE_Pre_Shoot_Only`): pre-shoot only, no de-emphasis.
123/// - `de_emphasis_only` (`TxFFE_De_Emphasis_Only`): de-emphasis only, no pre-shoot.
124/// - `no_ffe` (`TxFFE_No_FFE`): neither.
125///
126/// The default (no bit set) restricts nothing, for every backend: full TxFFE, as before
127/// the restrictions existed. The bits accompany a compliance test. Of the reference
128/// drivers that act on them, the Rockchip one does so only after the sink requests the DDE
129/// compliance pattern (LTP 4) on a lane; the AMD one applies them with every TxFFE setting
130/// during link training.
131///
132/// How to combine the bits is the PHY's to decide, because the reference implementations
133/// disagree and no public source settles it. The AMD display
134/// driver (`dpcs30_program_eq_setting`) treats each "only" bit as removing the other
135/// component, so both set leaves neither (not quite its `no_ffe` setting, which also
136/// changes the main cursor), and `no_ffe` overrides both. The Rockchip HDPTX PHY driver
137/// treats bits 1–2 as enabling their component, so both set gives full FFE, and does not
138/// read `no_ffe`; that reading applies only once a bit is set, never to the default. A
139/// backend documents which it follows. One that cannot restrict its TxFFE may ignore the
140/// bits, and says so: a compliance test then fails, not the link. The level in each lane's
141/// [`LaneEqParams`] still applies within what the restrictions allow.
142#[non_exhaustive]
143#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
144pub struct TxFfeRestrictions {
145    /// `TxFFE_Pre_Shoot_Only` (bit 1): use pre-shoot only.
146    pub pre_shoot_only: bool,
147    /// `TxFFE_De_Emphasis_Only` (bit 2): use de-emphasis only.
148    pub de_emphasis_only: bool,
149    /// `TxFFE_No_FFE` (bit 3): use no TxFFE.
150    pub no_ffe: bool,
151}
152
153impl TxFfeRestrictions {
154    /// Constructs `TxFfeRestrictions` from the three bits, in register order.
155    pub const fn new(pre_shoot_only: bool, de_emphasis_only: bool, no_ffe: bool) -> Self {
156        Self {
157            pre_shoot_only,
158            de_emphasis_only,
159            no_ffe,
160        }
161    }
162}
163
164/// Equalization parameters passed from link training to the PHY.
165///
166/// Carries each lane's TxFFE level, raised during FRL link training when the sink requests
167/// it (an FFE change, 0xE, in its link training requests), and the link-wide
168/// [`TxFfeRestrictions`] a compliance tester may set. `lane3` is `None` in 3-lane FRL mode.
169#[non_exhaustive]
170#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
171pub struct EqParams {
172    /// Equalization parameters for lane 0.
173    pub lane0: LaneEqParams,
174    /// Equalization parameters for lane 1.
175    pub lane1: LaneEqParams,
176    /// Equalization parameters for lane 2.
177    pub lane2: LaneEqParams,
178    /// Equalization parameters for lane 3. `None` in 3-lane FRL mode.
179    pub lane3: Option<LaneEqParams>,
180    /// Restrictions on the TxFFE components, for every lane. Defaults to none.
181    pub tx_ffe_restrictions: TxFfeRestrictions,
182}
183
184impl EqParams {
185    /// Create a new `EqParams` with default values.
186    pub fn new() -> Self {
187        Self::default()
188    }
189}
190
191/// FRL control of an HDMI 2.1 transmitter PHY.
192///
193/// Covers what FRL link training needs from the transmitter: FRL rate selection, link
194/// training patterns, FRL output mode, and each lane's TxFFE level (FRL's transmitter
195/// equalization, a combination of pre-shoot and de-emphasis) through
196/// [`adjust_equalization`](Self::adjust_equalization). TMDS is [`TmdsPhy`]'s, the source's
197/// scrambler included, and power is [`PhyPower`]'s. Further PHY configuration (lane mapping,
198/// spread-spectrum clocking and power states beyond off and on) is not covered yet; it is
199/// planned for when the mode-setting layer needs it.
200/// Vendor-specific register sequences are an implementation detail of each backend.
201///
202/// On a PHY that also implements [`TmdsPhy`], entering one mode leaves the other:
203/// [`set_frl_rate`](Self::set_frl_rate) with a rate leaves TMDS. [`TmdsPhy::stop_output`]
204/// on a PHY in FRL leaves FRL, as `set_frl_rate(NotSupported)` does.
205pub trait FrlPhy {
206    /// Error type returned by PHY operations; `Debug`, as the other PHY traits' errors are,
207    /// so generic code can format it.
208    type Error: core::fmt::Debug;
209
210    /// Select the FRL rate, or turn FRL off. Triggers the required lane reconfiguration
211    /// sequence.
212    ///
213    /// A rate enters FRL, leaving TMDS on a PHY that also does TMDS.
214    /// [`HdmiForumFrl::NotSupported`] turns FRL off and enters no other mode: entering TMDS
215    /// is [`TmdsPhy::configure`]'s.
216    ///
217    /// Returns once the PHY transmits at `rate`, after any bring-up its hardware needs to
218    /// get there — the Xilinx HDMI 2.1 transmitter, for example, holds a Nyquist clock
219    /// pattern until its link is up. Only the PHY knows when that is, so the sequence
220    /// belongs here; the link training layer sends no pattern of its own around it.
221    fn set_frl_rate(&mut self, rate: HdmiForumFrl) -> Result<(), Self::Error>;
222
223    /// Drive the given link training patterns on the physical lanes, one per lane.
224    fn send_ltp(&mut self, patterns: LanePatterns) -> Result<(), Self::Error>;
225
226    /// Select what the transmitter sends on the FRL lanes: gap characters only, or video,
227    /// data islands and control periods.
228    fn set_frl_output(&mut self, output: FrlOutput) -> Result<(), Self::Error>;
229
230    /// Apply equalization: each lane's TxFFE level, within the link-wide
231    /// [`TxFfeRestrictions`] in `params`. Each call carries the complete settings, so the
232    /// restrictions in force are always the last ones given.
233    fn adjust_equalization(&mut self, params: EqParams) -> Result<(), Self::Error>;
234}
235
236/// The TMDS bit clock ratio, as the sink's `TMDS_Bit_Clock_Ratio` bit selects it.
237///
238/// Deliberately exhaustive: it is one bit on the wire (`TMDS_Bit_Clock_Ratio`), with no room
239/// for a third value.
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
241pub enum TmdsClockRatio {
242    /// 1/10.
243    Div10,
244    /// 1/40.
245    Div40,
246}
247
248/// The video a TMDS link carries, as far as a PHY may need it.
249///
250/// Some PHYs are set up from the pixel clock and colour depth rather than from the character
251/// rate, and one character rate comes from several pixel clocks: for RGB and YCbCr 4:4:4 the
252/// rate is the pixel clock times the bits per component over 8, and for YCbCr 4:2:0 half
253/// that (dw-hdmi,
254/// torvalds/linux `e774d5f1b` `drivers/gpu/drm/bridge/synopsys/dw-hdmi.c:2008–2026`; i915,
255/// `drivers/gpu/drm/i915/display/intel_hdmi.c:1925–1937`). A PHY keyed by the character rate
256/// ignores this.
257#[non_exhaustive]
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259pub struct TmdsVideo {
260    /// The clock at which pixels reach the TMDS encoder, in kHz: pixel repetition included,
261    /// the deep-colour factor not. For a repeated mode it is the mode's own clock times
262    /// `pixel_repetition + 1`.
263    ///
264    /// Linux lists 720(1440)x480i (VIC 6) at 13 500 kHz with a double-clock flag
265    /// (torvalds/linux `e774d5f1b`, `drivers/gpu/drm/drm_edid.c:791–794`); this field is
266    /// 27 000 for it, with `pixel_repetition` 1. Drivers read such a mode either way: i915
267    /// doubles the clock for the port (`i915/display/intel_hdmi.c:2049–2052`, `2175–2176`),
268    /// while dw-hdmi takes the mode's clock as its pixel clock (`bridge/synopsys/dw-hdmi.c:2004`)
269    /// and refuses double-clocked modes (`:2940–2941`). The convention here is chosen, so
270    /// that a PHY keyed by the pixel clock needs no other field to find its rate.
271    pub pixel_clock_khz: u32,
272    /// Bits per colour component.
273    ///
274    /// The type is display-types' depth vocabulary, decoded from the EDID, so it names
275    /// depths (6 or 14 bits, for example) a PHY may not carry. [`TmdsPhy::configure`]
276    /// returns an error for a depth or a format the PHY cannot carry.
277    pub color_depth: ColorBitDepth,
278    /// The colour format. YCbCr 4:2:0 halves the character rate (dw-hdmi and i915, as cited
279    /// on [`TmdsVideo`]).
280    pub color_format: ColorFormat,
281    /// Pixel repetition: 0 for none, `n` for each pixel sent `n + 1` times.
282    pub pixel_repetition: u8,
283}
284
285impl TmdsVideo {
286    /// Constructs `TmdsVideo` with no pixel repetition.
287    pub const fn new(
288        pixel_clock_khz: u32,
289        color_depth: ColorBitDepth,
290        color_format: ColorFormat,
291    ) -> Self {
292        Self {
293            pixel_clock_khz,
294            color_depth,
295            color_format,
296            pixel_repetition: 0,
297        }
298    }
299
300    /// Sets the pixel repetition (0: none; `n`: each pixel sent `n + 1` times).
301    pub const fn with_pixel_repetition(mut self, pixel_repetition: u8) -> Self {
302        self.pixel_repetition = pixel_repetition;
303        self
304    }
305
306    /// The TMDS character rate this video gives, in kHz, rounded up: the
307    /// [`character_rate_khz`](TmdsPhyConfig::character_rate_khz) a [`TmdsPhyConfig`] for it
308    /// carries.
309    ///
310    /// [`pixel_clock_khz`](Self::pixel_clock_khz) times the deep-colour factor (×5/4 at 10
311    /// bits, ×3/2 at 12, ×2 at 16), except for YCbCr 4:2:2, which runs at the pixel clock at
312    /// any depth up to 12 bits, and halved for YCbCr 4:2:0. Pixel repetition is already in
313    /// the pixel clock. The DRM helper and dw-hdmi compute it so, and i915 agrees for the
314    /// formats it carries (torvalds/linux `e774d5f1b`:
315    /// `display/drm_hdmi_helper.c:225–257`, `bridge/synopsys/dw-hdmi.c:2008–2026`,
316    /// `i915/display/intel_hdmi.c:1925–1938`). They round to the nearest Hz; this rounds up to
317    /// the next kHz, so a rate just above a threshold, such as 340 000.5 kHz, is never taken
318    /// for one at or below it.
319    ///
320    /// `None` for a depth TMDS does not carry (6 or 14 bits, or one added to
321    /// [`ColorBitDepth`] later), YCbCr 4:2:2 above 12 bits (the helper refuses it), a format
322    /// added to [`ColorFormat`] later, or a rate above `u32::MAX` kHz.
323    #[must_use]
324    pub const fn character_rate_khz(&self) -> Option<u32> {
325        let (num, den): (u64, u64) = match self.color_depth {
326            ColorBitDepth::Depth8 => (1, 1),
327            ColorBitDepth::Depth10 => (5, 4),
328            ColorBitDepth::Depth12 => (3, 2),
329            ColorBitDepth::Depth16 => (2, 1),
330            _ => return None,
331        };
332        let (num, den) = match self.color_format {
333            ColorFormat::Rgb444 | ColorFormat::YCbCr444 => (num, den),
334            ColorFormat::YCbCr420 => (num, den * 2),
335            // 4:2:2 runs at the pixel clock up to 12 bits; the rest is a format added later.
336            ColorFormat::YCbCr422 if !matches!(self.color_depth, ColorBitDepth::Depth16) => (1, 1),
337            _ => return None,
338        };
339        let rate = (self.pixel_clock_khz as u64 * num).div_ceil(den);
340        if rate > u32::MAX as u64 {
341            None
342        } else {
343            Some(rate as u32)
344        }
345    }
346}
347
348/// What [`TmdsPhy::configure`] sets.
349///
350/// The caller guarantees that [`character_rate_khz`](Self::character_rate_khz) is the rate
351/// [`video`](Self::video) gives, rounded up, as [`TmdsVideo::character_rate_khz`] computes
352/// it. A PHY may configure itself from either: the character rate, or the video it comes
353/// from.
354#[non_exhaustive]
355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356pub struct TmdsPhyConfig {
357    /// The TMDS character rate, in kHz, rounded up and never truncated.
358    pub character_rate_khz: u32,
359    /// The TMDS bit clock ratio.
360    pub clock_ratio: TmdsClockRatio,
361    /// The video the link carries.
362    pub video: TmdsVideo,
363}
364
365impl TmdsPhyConfig {
366    /// Constructs `TmdsPhyConfig`.
367    pub const fn new(
368        character_rate_khz: u32,
369        clock_ratio: TmdsClockRatio,
370        video: TmdsVideo,
371    ) -> Self {
372        Self {
373            character_rate_khz,
374            clock_ratio,
375            video,
376        }
377    }
378}
379
380/// What a TMDS PHY can do, as [`TmdsPhy::capabilities`] reports it.
381///
382/// Hardware that cannot do something reports it here, never more than it can: [`new`]
383/// starts with no scrambler.
384///
385/// [`new`]: Self::new
386#[non_exhaustive]
387#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
388pub struct TmdsPhyCapabilities {
389    /// The source's own highest TMDS character rate, in kHz.
390    pub max_character_rate_khz: u32,
391    /// Whether the PHY has a TMDS scrambler.
392    ///
393    /// A field of its own, not derived from the ceiling: whether a link at exactly
394    /// 340 000 kHz is scrambled is the caller's threshold setting (spiritlevel's
395    /// `ScramblingThreshold`), so a PHY whose ceiling is 340 Mcsc and which has no scrambler
396    /// says so here.
397    pub scrambling: bool,
398    /// Whether the PHY can scramble at or below 340 Mcsc. Counts only with
399    /// [`scrambling`](Self::scrambling); read both through
400    /// [`scrambles_at_low_rate`](Self::scrambles_at_low_rate).
401    pub low_rate_scrambling: bool,
402}
403
404impl TmdsPhyCapabilities {
405    /// Constructs `TmdsPhyCapabilities` with the given ceiling and no scrambler.
406    pub const fn new(max_character_rate_khz: u32) -> Self {
407        Self {
408            max_character_rate_khz,
409            scrambling: false,
410            low_rate_scrambling: false,
411        }
412    }
413
414    /// Sets whether the PHY has a TMDS scrambler.
415    pub const fn with_scrambling(mut self, scrambling: bool) -> Self {
416        self.scrambling = scrambling;
417        self
418    }
419
420    /// Sets whether the PHY can scramble at or below 340 Mcsc.
421    pub const fn with_low_rate_scrambling(mut self, low_rate_scrambling: bool) -> Self {
422        self.low_rate_scrambling = low_rate_scrambling;
423        self
424    }
425
426    /// Whether the PHY can scramble at or below 340 Mcsc: it has a scrambler and can use it
427    /// at low rates. `low_rate_scrambling` without `scrambling` counts as false.
428    pub const fn scrambles_at_low_rate(&self) -> bool {
429        self.scrambling && self.low_rate_scrambling
430    }
431}
432
433/// TMDS control of an HDMI transmitter PHY.
434///
435/// What TMDS bring-up and tear-down need from the transmitter, and nothing more: the
436/// character rate and clock ratio, the source's scrambler, and starting and stopping the
437/// output. A trait of its own, so TMDS-only hardware implements nothing of FRL.
438///
439/// Not covered: electrical settings (swing, pre-emphasis, lane mapping), which are the
440/// implementation's; the video pipeline beyond what [`TmdsVideo`] gives the PHY; hotplug and
441/// RX sense; and power, which is [`PhyPower`]'s.
442///
443/// On a PHY that also implements [`FrlPhy`], entering one mode leaves the other:
444/// [`configure`](Self::configure) leaves FRL.
445pub trait TmdsPhy {
446    /// Error type returned by PHY operations.
447    type Error: core::fmt::Debug;
448
449    /// What the PHY can do. A plain report of what the implementation already knows.
450    fn capabilities(&self) -> TmdsPhyCapabilities;
451
452    /// Set the character rate and clock ratio, with the output stopped, and leave it
453    /// stopped. Enters TMDS mode, leaving FRL on a PHY that also does FRL.
454    ///
455    /// Called with the output running, it either returns an error (an implementation that
456    /// cannot reconfigure while transmitting) or stops the output first; when it succeeds,
457    /// the output is stopped. On a PHY that also implements [`PhyPower`] and is powered off,
458    /// it returns an error: the caller powers the PHY on first.
459    ///
460    /// The scrambler state afterwards is unspecified: an implementation may keep it, reset
461    /// it or set it from the rate. Callers set it with
462    /// [`set_scrambling`](Self::set_scrambling) after `configure`.
463    fn configure(&mut self, config: TmdsPhyConfig) -> Result<(), Self::Error>;
464
465    /// Turn the source's TMDS scrambler on or off, with the output running or stopped.
466    ///
467    /// `set_scrambling(false)` succeeds on a PHY without a scrambler
468    /// ([`TmdsPhyCapabilities::scrambling`] false), since plain links call it;
469    /// `set_scrambling(true)` on such a PHY returns an error.
470    fn set_scrambling(&mut self, enabled: bool) -> Result<(), Self::Error>;
471
472    /// Start TMDS output at the configured rate.
473    ///
474    /// Returns once the PHY transmits, after whatever its hardware needs to get there (a PLL
475    /// lock, a reset sequence): callers time from its return, so returning means on the
476    /// wire.
477    ///
478    /// Without a successful [`configure`](Self::configure) since the PHY was last powered
479    /// on (or since it was created, for a PHY without [`PhyPower`]), it returns an error.
480    fn start_output(&mut self) -> Result<(), Self::Error>;
481
482    /// Stop whatever the PHY transmits: TMDS clock and data or, on a PHY still in FRL, FRL
483    /// transmission. Keeps the PHY powered and its TMDS configuration, unlike
484    /// [`PhyPower::power_off`]. A PHY in FRL leaves FRL, as
485    /// [`FrlPhy::set_frl_rate`]`(NotSupported)` does, since nothing here can resume it.
486    ///
487    /// Callable in any state, powered off included; stopping a stopped output is not an
488    /// error.
489    fn stop_output(&mut self) -> Result<(), Self::Error>;
490}
491
492/// Power control of a transmitter PHY, shared by [`TmdsPhy`] and [`FrlPhy`].
493///
494/// A trait of its own, not a supertrait of the mode traits: link training and TMDS
495/// bring-up bound on a mode trait alone and never change the power, and a PHY that is
496/// always on implements the mode traits only. A caller that powers the PHY, on unplug and
497/// before a bring-up, bounds on `PhyPower` as well. One PHY implementing several of these
498/// traits may use one error type for all of them.
499///
500/// With both bounds, `P::Error` is ambiguous; generic code that wants one error type names
501/// it through one trait and ties the other to it:
502///
503/// ```
504/// use hdmi_hal::phy::{PhyPower, TmdsPhy, TmdsPhyConfig};
505///
506/// fn power_and_configure<P>(phy: &mut P, config: TmdsPhyConfig) -> Result<(), <P as TmdsPhy>::Error>
507/// where
508///     P: TmdsPhy + PhyPower<Error = <P as TmdsPhy>::Error>,
509/// {
510///     phy.power_on()?;
511///     phy.configure(config)
512/// }
513/// ```
514///
515/// For a PHY implementing both mode traits, entering one mode leaves the other:
516/// [`TmdsPhy::configure`] leaves FRL, and [`FrlPhy::set_frl_rate`] with a rate leaves TMDS;
517/// `set_frl_rate(NotSupported)` turns FRL off and enters nothing, as
518/// [`TmdsPhy::stop_output`] on a PHY in FRL does.
519pub trait PhyPower {
520    /// Error type returned by power operations.
521    type Error: core::fmt::Debug;
522
523    /// Power the PHY on, leaving the output stopped and no mode entered; the caller then
524    /// enters one, with [`TmdsPhy::configure`] or [`FrlPhy::set_frl_rate`].
525    ///
526    /// On a PHY that is already on it does nothing: it is not an error, and neither the
527    /// mode nor the output changes.
528    fn power_on(&mut self) -> Result<(), Self::Error>;
529
530    /// Power the PHY off: stop any output and leave no mode. Afterwards the PHY holds no
531    /// TMDS configuration and no FRL rate, so a bring-up must configure it again.
532    ///
533    /// Callable in any state; powering off a PHY that is off is not an error.
534    fn power_off(&mut self) -> Result<(), Self::Error>;
535}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540
541    #[test]
542    fn the_character_rate_follows_depth_and_format() {
543        let video = |clock, depth, format| TmdsVideo::new(clock, depth, format);
544        let rgb = ColorFormat::Rgb444;
545        // 4K60 at 8, 10, 12 and 16 bits.
546        assert_eq!(
547            video(594_000, ColorBitDepth::Depth8, rgb).character_rate_khz(),
548            Some(594_000)
549        );
550        assert_eq!(
551            video(297_000, ColorBitDepth::Depth10, rgb).character_rate_khz(),
552            Some(371_250)
553        );
554        assert_eq!(
555            video(297_000, ColorBitDepth::Depth12, rgb).character_rate_khz(),
556            Some(445_500)
557        );
558        assert_eq!(
559            video(297_000, ColorBitDepth::Depth16, rgb).character_rate_khz(),
560            Some(594_000)
561        );
562        // YCbCr 4:4:4 as RGB; 4:2:2 at the pixel clock up to 12 bits, none above.
563        let ycc = |format, depth| video(297_000, depth, format).character_rate_khz();
564        assert_eq!(
565            ycc(ColorFormat::YCbCr444, ColorBitDepth::Depth12),
566            Some(445_500)
567        );
568        assert_eq!(
569            ycc(ColorFormat::YCbCr422, ColorBitDepth::Depth8),
570            Some(297_000)
571        );
572        assert_eq!(
573            ycc(ColorFormat::YCbCr422, ColorBitDepth::Depth10),
574            Some(297_000)
575        );
576        assert_eq!(
577            ycc(ColorFormat::YCbCr422, ColorBitDepth::Depth12),
578            Some(297_000)
579        );
580        assert_eq!(ycc(ColorFormat::YCbCr422, ColorBitDepth::Depth16), None);
581        // 4:2:0 halves, after the deep-colour factor.
582        let yuv420 = ColorFormat::YCbCr420;
583        assert_eq!(
584            video(594_000, ColorBitDepth::Depth8, yuv420).character_rate_khz(),
585            Some(297_000)
586        );
587        assert_eq!(
588            video(594_000, ColorBitDepth::Depth10, yuv420).character_rate_khz(),
589            Some(371_250)
590        );
591        // Rounded up, never truncated: 272 001.25 kHz becomes 272 002.
592        assert_eq!(
593            video(217_601, ColorBitDepth::Depth10, rgb).character_rate_khz(),
594            Some(272_002)
595        );
596        assert_eq!(
597            video(1, ColorBitDepth::Depth8, yuv420).character_rate_khz(),
598            Some(1)
599        );
600        // Depths TMDS does not carry, and overflow.
601        assert_eq!(
602            video(148_500, ColorBitDepth::Depth6, rgb).character_rate_khz(),
603            None
604        );
605        assert_eq!(
606            video(148_500, ColorBitDepth::Depth14, rgb).character_rate_khz(),
607            None
608        );
609        assert_eq!(
610            video(u32::MAX, ColorBitDepth::Depth16, rgb).character_rate_khz(),
611            None
612        );
613        assert_eq!(
614            video(u32::MAX, ColorBitDepth::Depth8, rgb).character_rate_khz(),
615            Some(u32::MAX)
616        );
617        const RATE: Option<u32> =
618            TmdsVideo::new(148_500, ColorBitDepth::Depth8, ColorFormat::Rgb444)
619                .character_rate_khz();
620        assert_eq!(RATE, Some(148_500));
621    }
622    use display_types::cea861::hdmi_forum::HdmiForumFrl;
623
624    /// A minimal `FrlPhy` that records what it is given. The tests that drive it method by
625    /// method check little beyond recording — they show that the trait can be implemented
626    /// and used for each method, and they keep this implementation covered. Behaviour is
627    /// tested where it lives: in plumbob, against its simulated PHY.
628    struct MockPhy {
629        frl_rate: Option<HdmiForumFrl>,
630        eq_calls: u32,
631        last_eq: Option<EqParams>,
632        frl_output: Option<FrlOutput>,
633        last_ltp: Option<LanePatterns>,
634    }
635
636    impl MockPhy {
637        fn new() -> Self {
638            Self {
639                frl_rate: None,
640                eq_calls: 0,
641                last_eq: None,
642                frl_output: None,
643                last_ltp: None,
644            }
645        }
646    }
647
648    impl FrlPhy for MockPhy {
649        type Error = core::convert::Infallible;
650
651        fn send_ltp(&mut self, patterns: LanePatterns) -> Result<(), Self::Error> {
652            self.last_ltp = Some(patterns);
653            Ok(())
654        }
655
656        fn set_frl_output(&mut self, output: FrlOutput) -> Result<(), Self::Error> {
657            self.frl_output = Some(output);
658            Ok(())
659        }
660
661        fn set_frl_rate(&mut self, rate: HdmiForumFrl) -> Result<(), Self::Error> {
662            self.frl_rate = Some(rate);
663            Ok(())
664        }
665
666        fn adjust_equalization(&mut self, params: EqParams) -> Result<(), Self::Error> {
667            self.eq_calls += 1;
668            self.last_eq = Some(params);
669            Ok(())
670        }
671    }
672
673    #[test]
674    fn ltp_pattern_values_match_scdc_encoding() {
675        assert_eq!(LtpPattern::AllOnes.value(), 1);
676        assert_eq!(LtpPattern::AllZeros.value(), 2);
677        assert_eq!(LtpPattern::NyquistClock.value(), 3);
678        assert_eq!(LtpPattern::DdeCompliance.value(), 4);
679        assert_eq!(LtpPattern::Lfsr0.value(), 5);
680        assert_eq!(LtpPattern::Lfsr1.value(), 6);
681        assert_eq!(LtpPattern::Lfsr2.value(), 7);
682        assert_eq!(LtpPattern::Lfsr3.value(), 8);
683    }
684
685    #[test]
686    fn ltp_pattern_clone_eq() {
687        let a = LtpPattern::Lfsr1;
688        assert_eq!(a, a);
689        assert_ne!(LtpPattern::Lfsr0, LtpPattern::Lfsr1);
690    }
691
692    #[test]
693    fn lane_patterns_default_is_no_pattern() {
694        let p = LanePatterns::default();
695        assert_eq!(p.lane0, None);
696        assert_eq!(p.lane1, None);
697        assert_eq!(p.lane2, None);
698        assert_eq!(p.lane3, None);
699    }
700
701    #[test]
702    fn send_ltp_records_patterns() {
703        let mut phy = MockPhy::new();
704        let patterns = LanePatterns {
705            lane0: Some(LtpPattern::Lfsr0),
706            lane1: Some(LtpPattern::Lfsr1),
707            lane2: Some(LtpPattern::Lfsr2),
708            lane3: None,
709        };
710        phy.send_ltp(patterns).unwrap();
711        assert_eq!(phy.last_ltp, Some(patterns));
712    }
713
714    #[test]
715    fn send_ltp_updates_on_each_call() {
716        let mut phy = MockPhy::new();
717        let first = LanePatterns {
718            lane0: Some(LtpPattern::Lfsr0),
719            ..LanePatterns::default()
720        };
721        let second = LanePatterns {
722            lane0: Some(LtpPattern::NyquistClock),
723            ..first
724        };
725        phy.send_ltp(first).unwrap();
726        phy.send_ltp(second).unwrap();
727        assert_eq!(phy.last_ltp, Some(second));
728    }
729
730    #[test]
731    fn eq_params_constructors_are_equivalent() {
732        let _a = EqParams::new();
733        let _b = EqParams::default();
734    }
735
736    #[test]
737    fn set_frl_rate_records_rate() {
738        let mut phy = MockPhy::new();
739        phy.set_frl_rate(HdmiForumFrl::Rate6Gbps4Lanes).unwrap();
740        assert_eq!(phy.frl_rate, Some(HdmiForumFrl::Rate6Gbps4Lanes));
741    }
742
743    #[test]
744    fn set_frl_rate_not_supported_is_valid() {
745        let mut phy = MockPhy::new();
746        phy.set_frl_rate(HdmiForumFrl::NotSupported).unwrap();
747        assert_eq!(phy.frl_rate, Some(HdmiForumFrl::NotSupported));
748    }
749
750    #[test]
751    fn set_frl_rate_can_be_updated() {
752        let mut phy = MockPhy::new();
753        phy.set_frl_rate(HdmiForumFrl::Rate3Gbps3Lanes).unwrap();
754        phy.set_frl_rate(HdmiForumFrl::Rate12Gbps4Lanes).unwrap();
755        assert_eq!(phy.frl_rate, Some(HdmiForumFrl::Rate12Gbps4Lanes));
756    }
757
758    #[test]
759    fn set_frl_output_records_mode() {
760        let mut phy = MockPhy::new();
761        phy.set_frl_output(FrlOutput::GapOnly).unwrap();
762        assert_eq!(phy.frl_output, Some(FrlOutput::GapOnly));
763    }
764
765    #[test]
766    fn set_frl_output_can_be_switched() {
767        let mut phy = MockPhy::new();
768        phy.set_frl_output(FrlOutput::GapOnly).unwrap();
769        phy.set_frl_output(FrlOutput::Active).unwrap();
770        assert_eq!(phy.frl_output, Some(FrlOutput::Active));
771    }
772
773    #[test]
774    fn value_types_can_be_hashed() {
775        extern crate std;
776        use std::collections::HashSet;
777        let patterns: HashSet<LanePatterns> = [LanePatterns::default(), LanePatterns::default()]
778            .into_iter()
779            .collect();
780        assert_eq!(patterns.len(), 1);
781        let outputs: HashSet<FrlOutput> = [FrlOutput::GapOnly, FrlOutput::Active].into();
782        assert_eq!(outputs.len(), 2);
783        let levels: HashSet<TxFfeLevel> = [TxFfeLevel::MAX, TxFfeLevel::default()].into();
784        assert_eq!(levels.len(), 2);
785        let eq: HashSet<EqParams> = [EqParams::new(), EqParams::new()].into();
786        assert_eq!(eq.len(), 1);
787        let ltp: HashSet<LtpPattern> = [LtpPattern::Lfsr0, LtpPattern::Lfsr0].into();
788        assert_eq!(ltp.len(), 1);
789    }
790
791    #[test]
792    fn tx_ffe_level_accepts_0_to_7() {
793        for level in 0..=7 {
794            assert_eq!(TxFfeLevel::new(level).map(TxFfeLevel::value), Some(level));
795        }
796    }
797
798    #[test]
799    fn tx_ffe_level_rejects_above_7() {
800        assert_eq!(TxFfeLevel::new(8), None);
801        assert_eq!(TxFfeLevel::new(u8::MAX), None);
802    }
803
804    #[test]
805    fn tx_ffe_level_max_and_default() {
806        assert_eq!(TxFfeLevel::MAX.value(), 7);
807        assert_eq!(TxFfeLevel::default().value(), 0);
808        assert!(TxFfeLevel::default() < TxFfeLevel::MAX);
809    }
810
811    #[test]
812    fn lane_eq_params_default_tx_ffe_level_is_0() {
813        assert_eq!(LaneEqParams::default().tx_ffe_level, TxFfeLevel::default());
814    }
815
816    #[test]
817    fn tx_ffe_restrictions_new_takes_the_bits_in_register_order() {
818        let r = TxFfeRestrictions::new(true, false, false);
819        assert!(r.pre_shoot_only && !r.de_emphasis_only && !r.no_ffe);
820        let r = TxFfeRestrictions::new(false, true, false);
821        assert!(!r.pre_shoot_only && r.de_emphasis_only && !r.no_ffe);
822        let r = TxFfeRestrictions::new(false, false, true);
823        assert!(!r.pre_shoot_only && !r.de_emphasis_only && r.no_ffe);
824        // Combinations are carried as written; the PHY decides what they mean.
825        let both = TxFfeRestrictions::new(true, true, false);
826        assert!(both.pre_shoot_only && both.de_emphasis_only);
827    }
828
829    #[test]
830    fn eq_params_restrict_nothing_by_default() {
831        assert_eq!(
832            TxFfeRestrictions::default(),
833            TxFfeRestrictions::new(false, false, false)
834        );
835        assert_eq!(
836            EqParams::new().tx_ffe_restrictions,
837            TxFfeRestrictions::default()
838        );
839    }
840
841    #[test]
842    fn adjust_equalization_records_per_lane_levels() {
843        let mut phy = MockPhy::new();
844        let mut params = EqParams::new();
845        params.lane1.tx_ffe_level = TxFfeLevel::MAX;
846        phy.adjust_equalization(params).unwrap();
847        let last = phy.last_eq.unwrap();
848        assert_eq!(last, params);
849        assert_eq!(last.lane0.tx_ffe_level.value(), 0);
850        assert_eq!(last.lane1.tx_ffe_level.value(), 7);
851    }
852
853    #[test]
854    fn adjust_equalization_tracks_call_count() {
855        let mut phy = MockPhy::new();
856        phy.adjust_equalization(EqParams::new()).unwrap();
857        phy.adjust_equalization(EqParams::new()).unwrap();
858        assert_eq!(phy.eq_calls, 2);
859    }
860
861    /// A minimal `TmdsPhy` that records what it is given, as `MockPhy` does for `FrlPhy`.
862    /// Behaviour is tested where it lives: in spiritlevel, against its simulated PHY.
863    struct MockTmdsPhy {
864        config: Option<TmdsPhyConfig>,
865        scrambling: Option<bool>,
866        output: bool,
867    }
868
869    impl TmdsPhy for MockTmdsPhy {
870        type Error = core::convert::Infallible;
871
872        fn capabilities(&self) -> TmdsPhyCapabilities {
873            TmdsPhyCapabilities::new(600_000)
874                .with_scrambling(true)
875                .with_low_rate_scrambling(true)
876        }
877
878        fn configure(&mut self, config: TmdsPhyConfig) -> Result<(), Self::Error> {
879            self.config = Some(config);
880            Ok(())
881        }
882
883        fn set_scrambling(&mut self, enabled: bool) -> Result<(), Self::Error> {
884            self.scrambling = Some(enabled);
885            Ok(())
886        }
887
888        fn start_output(&mut self) -> Result<(), Self::Error> {
889            self.output = true;
890            Ok(())
891        }
892
893        fn stop_output(&mut self) -> Result<(), Self::Error> {
894            self.output = false;
895            Ok(())
896        }
897    }
898
899    const VIDEO_4K60: TmdsVideo = TmdsVideo::new(
900        594_000,
901        display_types::ColorBitDepth::Depth8,
902        display_types::ColorFormat::Rgb444,
903    );
904
905    #[test]
906    fn tmds_video_new_has_no_pixel_repetition() {
907        assert_eq!(VIDEO_4K60.pixel_clock_khz, 594_000);
908        assert_eq!(VIDEO_4K60.color_depth, display_types::ColorBitDepth::Depth8);
909        assert_eq!(VIDEO_4K60.color_format, display_types::ColorFormat::Rgb444);
910        assert_eq!(VIDEO_4K60.pixel_repetition, 0);
911        assert_eq!(VIDEO_4K60.with_pixel_repetition(1).pixel_repetition, 1);
912        // At run time as well as in a const, so coverage sees the constructor run.
913        let video = TmdsVideo::new(
914            594_000,
915            display_types::ColorBitDepth::Depth8,
916            display_types::ColorFormat::Rgb444,
917        );
918        assert_eq!(video, VIDEO_4K60);
919    }
920
921    #[test]
922    fn tmds_phy_config_new_takes_its_fields_in_order() {
923        const CONFIG: TmdsPhyConfig =
924            TmdsPhyConfig::new(594_000, TmdsClockRatio::Div40, VIDEO_4K60);
925        assert_eq!(CONFIG.character_rate_khz, 594_000);
926        assert_eq!(CONFIG.clock_ratio, TmdsClockRatio::Div40);
927        assert_eq!(CONFIG.video, VIDEO_4K60);
928    }
929
930    #[test]
931    fn tmds_phy_capabilities_new_reports_no_scrambler() {
932        let caps = TmdsPhyCapabilities::new(340_000);
933        assert_eq!(caps.max_character_rate_khz, 340_000);
934        assert!(!caps.scrambling);
935        assert!(!caps.low_rate_scrambling);
936        let caps = caps.with_scrambling(true).with_low_rate_scrambling(true);
937        assert!(caps.scrambling && caps.low_rate_scrambling);
938    }
939
940    #[test]
941    fn colour_types_are_display_types_at_both_paths() {
942        let depth: ColorBitDepth = display_types::ColorBitDepth::Depth10;
943        let _: crate::ColorBitDepth = depth;
944        let format: ColorFormat = display_types::ColorFormat::YCbCr420;
945        let _: crate::ColorFormat = format;
946    }
947
948    #[test]
949    fn low_rate_scrambling_counts_only_with_a_scrambler() {
950        let base = TmdsPhyCapabilities::new(600_000);
951        assert!(!base.scrambles_at_low_rate());
952        assert!(!base.with_low_rate_scrambling(true).scrambles_at_low_rate());
953        assert!(!base.with_scrambling(true).scrambles_at_low_rate());
954        let both = base.with_scrambling(true).with_low_rate_scrambling(true);
955        assert!(both.scrambles_at_low_rate());
956    }
957
958    #[test]
959    fn tmds_phy_records_configure_scrambling_and_output() {
960        let mut phy = MockTmdsPhy {
961            config: None,
962            scrambling: None,
963            output: false,
964        };
965        assert!(phy.capabilities().scrambling);
966        let config = TmdsPhyConfig::new(594_000, TmdsClockRatio::Div40, VIDEO_4K60);
967        phy.stop_output().unwrap();
968        phy.configure(config).unwrap();
969        phy.set_scrambling(true).unwrap();
970        phy.start_output().unwrap();
971        assert_eq!(phy.config, Some(config));
972        assert_eq!(phy.scrambling, Some(true));
973        assert!(phy.output);
974        phy.set_scrambling(false).unwrap();
975        phy.stop_output().unwrap();
976        assert_eq!(phy.scrambling, Some(false));
977        assert!(!phy.output);
978    }
979
980    /// A PHY with power, implementing both `TmdsPhy` and `PhyPower` with one error type, as
981    /// the trait's documentation allows.
982    struct PoweredPhy {
983        tmds: MockTmdsPhy,
984        powered: bool,
985    }
986
987    impl PhyPower for PoweredPhy {
988        type Error = core::convert::Infallible;
989
990        fn power_on(&mut self) -> Result<(), Self::Error> {
991            self.powered = true;
992            Ok(())
993        }
994
995        fn power_off(&mut self) -> Result<(), Self::Error> {
996            self.powered = false;
997            self.tmds.output = false;
998            self.tmds.config = None;
999            Ok(())
1000        }
1001    }
1002
1003    impl TmdsPhy for PoweredPhy {
1004        type Error = <Self as PhyPower>::Error;
1005
1006        fn capabilities(&self) -> TmdsPhyCapabilities {
1007            self.tmds.capabilities()
1008        }
1009
1010        fn configure(&mut self, config: TmdsPhyConfig) -> Result<(), Self::Error> {
1011            self.tmds.configure(config)
1012        }
1013
1014        fn set_scrambling(&mut self, enabled: bool) -> Result<(), Self::Error> {
1015            self.tmds.set_scrambling(enabled)
1016        }
1017
1018        fn start_output(&mut self) -> Result<(), Self::Error> {
1019            self.tmds.start_output()
1020        }
1021
1022        fn stop_output(&mut self) -> Result<(), Self::Error> {
1023            self.tmds.stop_output()
1024        }
1025    }
1026
1027    /// A caller that powers the PHY bounds on both traits; it drives every `TmdsPhy` method,
1028    /// so the forwarding to the inner mock is checked too.
1029    fn power_cycle<P: PhyPower + TmdsPhy>(phy: &mut P, config: TmdsPhyConfig) {
1030        phy.power_off().unwrap();
1031        phy.power_off().unwrap();
1032        phy.power_on().unwrap();
1033        phy.power_on().unwrap();
1034        phy.stop_output().unwrap();
1035        phy.configure(config).unwrap();
1036        let scrambling = phy.capabilities().scrambling;
1037        phy.set_scrambling(scrambling).unwrap();
1038        phy.start_output().unwrap();
1039    }
1040
1041    #[test]
1042    fn phy_power_composes_with_a_mode_trait() {
1043        let mut phy = PoweredPhy {
1044            tmds: MockTmdsPhy {
1045                config: None,
1046                scrambling: None,
1047                output: true,
1048            },
1049            powered: true,
1050        };
1051        let config = TmdsPhyConfig::new(594_000, TmdsClockRatio::Div40, VIDEO_4K60);
1052        power_cycle(&mut phy, config);
1053        assert!(phy.powered && phy.tmds.output);
1054        assert_eq!(phy.tmds.config, Some(config));
1055        assert_eq!(phy.tmds.scrambling, Some(true));
1056        phy.power_off().unwrap();
1057        assert!(!phy.powered && !phy.tmds.output);
1058        assert_eq!(phy.tmds.config, None);
1059    }
1060
1061    /// One PHY implementing all three traits with one error type, keeping track of the
1062    /// mode so the mode rule can be checked.
1063    #[derive(Debug, PartialEq, Eq)]
1064    enum Mode {
1065        None,
1066        Frl(HdmiForumFrl),
1067        Tmds,
1068    }
1069
1070    struct FullPhy {
1071        mode: Mode,
1072        powered: bool,
1073    }
1074
1075    #[derive(Debug, PartialEq, Eq)]
1076    struct PhyError;
1077
1078    impl FrlPhy for FullPhy {
1079        type Error = PhyError;
1080
1081        fn set_frl_rate(&mut self, rate: HdmiForumFrl) -> Result<(), PhyError> {
1082            if !self.powered {
1083                return Err(PhyError);
1084            }
1085            self.mode = match rate {
1086                HdmiForumFrl::NotSupported => Mode::None,
1087                rate => Mode::Frl(rate),
1088            };
1089            Ok(())
1090        }
1091
1092        fn send_ltp(&mut self, _patterns: LanePatterns) -> Result<(), PhyError> {
1093            Ok(())
1094        }
1095
1096        fn set_frl_output(&mut self, _output: FrlOutput) -> Result<(), PhyError> {
1097            Ok(())
1098        }
1099
1100        fn adjust_equalization(&mut self, _params: EqParams) -> Result<(), PhyError> {
1101            Ok(())
1102        }
1103    }
1104
1105    impl TmdsPhy for FullPhy {
1106        type Error = PhyError;
1107
1108        fn capabilities(&self) -> TmdsPhyCapabilities {
1109            TmdsPhyCapabilities::new(600_000).with_scrambling(true)
1110        }
1111
1112        fn configure(&mut self, _config: TmdsPhyConfig) -> Result<(), PhyError> {
1113            if !self.powered {
1114                return Err(PhyError);
1115            }
1116            self.mode = Mode::Tmds;
1117            Ok(())
1118        }
1119
1120        fn set_scrambling(&mut self, _enabled: bool) -> Result<(), PhyError> {
1121            Ok(())
1122        }
1123
1124        fn start_output(&mut self) -> Result<(), PhyError> {
1125            if self.mode == Mode::Tmds {
1126                Ok(())
1127            } else {
1128                Err(PhyError)
1129            }
1130        }
1131
1132        fn stop_output(&mut self) -> Result<(), PhyError> {
1133            if matches!(self.mode, Mode::Frl(_)) {
1134                self.mode = Mode::None;
1135            }
1136            Ok(())
1137        }
1138    }
1139
1140    impl PhyPower for FullPhy {
1141        type Error = PhyError;
1142
1143        fn power_on(&mut self) -> Result<(), PhyError> {
1144            self.powered = true;
1145            Ok(())
1146        }
1147
1148        fn power_off(&mut self) -> Result<(), PhyError> {
1149            self.powered = false;
1150            self.mode = Mode::None;
1151            Ok(())
1152        }
1153    }
1154
1155    /// FRL training gives up and the link falls back to TMDS, with one error type for all
1156    /// three traits, named through `TmdsPhy` as `PhyPower`'s documentation shows.
1157    fn fall_back_to_tmds<P>(phy: &mut P, config: TmdsPhyConfig) -> Result<(), <P as TmdsPhy>::Error>
1158    where
1159        P: TmdsPhy
1160            + FrlPhy<Error = <P as TmdsPhy>::Error>
1161            + PhyPower<Error = <P as TmdsPhy>::Error>,
1162    {
1163        phy.power_on()?;
1164        phy.set_frl_rate(HdmiForumFrl::Rate6Gbps4Lanes)?;
1165        phy.send_ltp(LanePatterns::default())?;
1166        phy.adjust_equalization(EqParams::new())?;
1167        phy.set_frl_output(FrlOutput::GapOnly)?;
1168        phy.set_frl_rate(HdmiForumFrl::NotSupported)?;
1169        phy.stop_output()?;
1170        phy.configure(config)?;
1171        let scrambling = phy.capabilities().scrambling;
1172        phy.set_scrambling(scrambling)?;
1173        phy.start_output()
1174    }
1175
1176    #[test]
1177    fn one_type_implements_all_three_traits_with_one_error_type() {
1178        let mut phy = FullPhy {
1179            mode: Mode::None,
1180            powered: false,
1181        };
1182        let config = TmdsPhyConfig::new(594_000, TmdsClockRatio::Div40, VIDEO_4K60);
1183        assert_eq!(phy.configure(config), Err(PhyError));
1184        assert_eq!(
1185            phy.set_frl_rate(HdmiForumFrl::Rate3Gbps3Lanes),
1186            Err(PhyError)
1187        );
1188        fall_back_to_tmds(&mut phy, config).unwrap();
1189        assert_eq!(phy.mode, Mode::Tmds);
1190        // A rate leaves TMDS; stop_output on a PHY in FRL leaves FRL.
1191        phy.set_frl_rate(HdmiForumFrl::Rate3Gbps3Lanes).unwrap();
1192        assert_eq!(phy.mode, Mode::Frl(HdmiForumFrl::Rate3Gbps3Lanes));
1193        TmdsPhy::stop_output(&mut phy).unwrap();
1194        assert_eq!(phy.mode, Mode::None);
1195        assert_eq!(phy.start_output(), Err(PhyError));
1196        phy.power_off().unwrap();
1197        assert!(!phy.powered);
1198    }
1199}