Skip to main content

spiritlevel/
params.rs

1//! The chosen link: `TmdsLinkParams`, its `choose` function, and why the link is or is
2//! not scrambled (`ScramblingDecision`, `ScramblingOff`).
3
4use crate::error::ParamsError;
5use crate::types::{
6    ClockRatio, ScramblingThreshold, SinkTmdsConfig, SinkTmdsFacts, SourceTmdsFacts,
7    TmdsConfigGate, TmdsPolicy,
8};
9
10/// The rate, in kHz, that the threshold is measured against: 340 Mcsc.
11const THRESHOLD_KHZ: u32 = 340_000;
12
13/// Why the link is or is not scrambled.
14#[non_exhaustive]
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum ScramblingDecision {
17    /// The rate is above the threshold, so the link is scrambled at 1/40.
18    Required,
19    /// The rate is at or below the threshold, and the source, the sink and the policy
20    /// all allow scrambling.
21    LowRate,
22    /// The link is 1/10 and not scrambled: the rate is at or below the threshold, or it
23    /// is exactly 340 000 kHz under [`ScramblingThreshold::AtOrAbove340`] on a sink
24    /// without SCDC or scrambling support or a source without a scrambler (then
25    /// `no_scdc`, `no_scrambling_support` or `source_cannot` is set).
26    Off(ScramblingOff),
27}
28
29/// Every condition that keeps a 1/10 link unscrambled.
30///
31/// At least one flag is set. Each is judged on its own fact, independently of the
32/// others: a sink without SCDC that also does not declare `LTE_340Mcsc_scramble` has
33/// both flags set.
34#[non_exhaustive]
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub struct ScramblingOff {
37    /// The sink has no SCDC, so it cannot be told to expect scrambling.
38    pub no_scdc: bool,
39    /// The sink does not support scrambling
40    /// ([`SinkTmdsFacts::scrambling_supported`] is clear).
41    pub no_scrambling_support: bool,
42    /// The sink does not declare `LTE_340Mcsc_scramble`.
43    pub sink_does_not_declare: bool,
44    /// The source cannot scramble at or below 340 Mcsc: it has no scrambler, or cannot use
45    /// it at low rates.
46    pub source_cannot: bool,
47    /// The policy does not permit scrambling at or below the threshold.
48    pub policy_off: bool,
49}
50
51/// The chosen TMDS link: clock ratio, scrambling, and the sink's `TMDS_Config`.
52///
53/// Built only by [`choose`](Self::choose), so the sink's value always matches the
54/// link the source runs.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub struct TmdsLinkParams {
57    rate_khz: u32,
58    clock_ratio: ClockRatio,
59    decision: ScramblingDecision,
60    sink_config: Option<SinkTmdsConfig>,
61    sink: SinkTmdsFacts,
62    source: SourceTmdsFacts,
63    policy: TmdsPolicy,
64}
65
66impl TmdsLinkParams {
67    /// Chooses the link for a TMDS character rate.
68    ///
69    /// `rate_khz` is the TMDS character rate in kHz, rounded up: truncating would put a
70    /// rate just above 340 000 kHz on the wrong side of the threshold.
71    ///
72    /// - Above the policy's threshold, the link is 1/40 and scrambled, on a sink with
73    ///   SCDC and scrambling support.
74    /// - At or below it, the link is 1/10, and scrambled when the source, the sink
75    ///   (SCDC, scrambling support and `LTE_340Mcsc_scramble`) and the policy all allow
76    ///   it; otherwise every reason is reported.
77    /// - At exactly 340 000 kHz with [`ScramblingThreshold::AtOrAbove340`], a sink
78    ///   without SCDC or scrambling support, or a source without a scrambler, gets the
79    ///   plain 1/10 link, and the flag that says why.
80    /// - A source without a scrambler is treated as a sink that cannot take scrambling:
81    ///   refused above 340 000 kHz, unscrambled at or below.
82    /// - A sink without SCDC gets no `TMDS_Config` value, nor does a plain link on a sink
83    ///   without scrambling support under [`TmdsConfigGate::ScramblingSink`].
84    ///
85    /// # Errors
86    ///
87    /// [`ParamsError::AboveSourceMaximum`] for a rate above the source's own maximum,
88    /// checked first. [`ParamsError::ScramblingUnsupported`] for a rate above 340 000 kHz
89    /// on a sink without SCDC or scrambling support, or from a source without a scrambler.
90    ///
91    /// # Example
92    ///
93    /// ```
94    /// use spiritlevel::{
95    ///     ClockRatio, ScramblingDecision, SinkTmdsFacts, SourceTmdsFacts, TmdsLinkParams,
96    ///     TmdsPolicy,
97    /// };
98    ///
99    /// // 4K at 60 Hz, 8 bpc RGB: 594 MHz.
100    /// let sink = SinkTmdsFacts::new(true, true, false);
101    /// let source = SourceTmdsFacts::new(false);
102    /// let link = TmdsLinkParams::choose(594_000, sink, source, TmdsPolicy::DEFAULT)?;
103    ///
104    /// assert_eq!(link.clock_ratio(), ClockRatio::Div40);
105    /// assert_eq!(link.scrambling_decision(), ScramblingDecision::Required);
106    /// let config = link.sink_config().expect("the sink has SCDC");
107    /// assert!(config.scrambling_enable && config.high_tmds_clock_ratio);
108    /// # Ok::<(), spiritlevel::ParamsError>(())
109    /// ```
110    pub const fn choose(
111        rate_khz: u32,
112        sink: SinkTmdsFacts,
113        source: SourceTmdsFacts,
114        policy: TmdsPolicy,
115    ) -> Result<Self, ParamsError> {
116        if rate_khz > source.max_character_rate_khz {
117            // Before anything else: a link the source cannot drive gets no sink configuration.
118            return Err(ParamsError::AboveSourceMaximum {
119                rate_khz,
120                max_khz: source.max_character_rate_khz,
121            });
122        }
123        let above_threshold = match policy.threshold {
124            ScramblingThreshold::Above340 => rate_khz > THRESHOLD_KHZ,
125            ScramblingThreshold::AtOrAbove340 => rate_khz >= THRESHOLD_KHZ,
126        };
127        let sink_can_scramble = sink.scdc_present && sink.scrambling_supported;
128
129        if above_threshold && sink_can_scramble && source.scrambling {
130            return Ok(Self {
131                rate_khz,
132                clock_ratio: ClockRatio::Div40,
133                decision: ScramblingDecision::Required,
134                sink_config: Some(SinkTmdsConfig::new(true, true)),
135                sink,
136                source,
137                policy,
138            });
139        }
140        if rate_khz > THRESHOLD_KHZ {
141            // Above the threshold under either setting, and the sink cannot take it or the
142            // source cannot scramble.
143            return Err(ParamsError::ScramblingUnsupported {
144                rate_khz,
145                no_scdc: !sink.scdc_present,
146                no_scrambling_support: !sink.scrambling_supported,
147                source_cannot_scramble: !source.scrambling,
148            });
149        }
150
151        // At or below the threshold, or exactly 340 000 kHz on a sink without SCDC or
152        // scrambling support or a source without a scrambler (one of those flags is then
153        // set).
154        let off = ScramblingOff {
155            no_scdc: !sink.scdc_present,
156            no_scrambling_support: !sink.scrambling_supported,
157            sink_does_not_declare: !sink.lte_340mcsc_scramble,
158            source_cannot: !(source.scrambling && source.low_rate_scrambling),
159            policy_off: !policy.low_rate_scrambling,
160        };
161        let scrambled = !(off.no_scdc
162            || off.no_scrambling_support
163            || off.sink_does_not_declare
164            || off.source_cannot
165            || off.policy_off);
166        let decision = if scrambled {
167            ScramblingDecision::LowRate
168        } else {
169            ScramblingDecision::Off(off)
170        };
171        // A scrambled link always writes; a plain one as the policy's gate says.
172        let write_due = sink.scdc_present
173            && (scrambled
174                || match policy.tmds_config_gate {
175                    TmdsConfigGate::ScramblingSink => sink.scrambling_supported,
176                    _ => true,
177                });
178        let sink_config = if write_due {
179            Some(SinkTmdsConfig::new(scrambled, false))
180        } else {
181            None
182        };
183        Ok(Self {
184            rate_khz,
185            clock_ratio: ClockRatio::Div10,
186            decision,
187            sink_config,
188            sink,
189            source,
190            policy,
191        })
192    }
193
194    /// The TMDS character rate the link was chosen for, in kHz.
195    #[must_use]
196    pub const fn rate_khz(&self) -> u32 {
197        self.rate_khz
198    }
199
200    /// The TMDS bit clock ratio.
201    #[must_use]
202    pub const fn clock_ratio(&self) -> ClockRatio {
203        self.clock_ratio
204    }
205
206    /// Whether the link is scrambled: true for [`ScramblingDecision::Required`] and
207    /// [`ScramblingDecision::LowRate`].
208    #[must_use]
209    pub const fn scrambling(&self) -> bool {
210        matches!(
211            self.decision,
212            ScramblingDecision::Required | ScramblingDecision::LowRate
213        )
214    }
215
216    /// Why the link is or is not scrambled.
217    #[must_use]
218    pub const fn scrambling_decision(&self) -> ScramblingDecision {
219        self.decision
220    }
221
222    /// What the sink's `TMDS_Config` must hold; `None` exactly when no write is due: a sink
223    /// without SCDC, or a plain link the policy's [`TmdsConfigGate`] leaves unwritten.
224    #[must_use]
225    pub const fn sink_config(&self) -> Option<SinkTmdsConfig> {
226        self.sink_config
227    }
228
229    /// The sink facts the link was chosen from: what the link assumes about the sink.
230    #[must_use]
231    pub const fn sink(&self) -> SinkTmdsFacts {
232        self.sink
233    }
234
235    /// Whether the link still fits a sink with the facts `sink`: [`choose`](Self::choose),
236    /// with the source facts and the policy this link was chosen with, gives the same clock
237    /// ratio, scrambling and `TMDS_Config` value. A fact the link does not depend on (such
238    /// as [`SinkTmdsFacts::frl_capable`], or `LTE_340Mcsc_scramble` on a 1/40 link) may
239    /// differ.
240    #[must_use]
241    pub fn fits(&self, sink: SinkTmdsFacts) -> bool {
242        match Self::choose(self.rate_khz, sink, self.source, self.policy) {
243            Ok(other) => {
244                other.clock_ratio == self.clock_ratio
245                    && other.scrambling() == self.scrambling()
246                    && other.sink_config == self.sink_config
247            }
248            Err(_) => false,
249        }
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    #[test]
258    fn a_link_fits_facts_that_choose_the_same_link() {
259        let sink = SinkTmdsFacts::new(true, true, false);
260        let source = SourceTmdsFacts::new(false);
261        let link = TmdsLinkParams::choose(594_000, sink, source, TmdsPolicy::DEFAULT).unwrap();
262        assert!(link.fits(sink));
263        assert!(link.fits(sink.with_frl_capable(false)));
264        assert!(link.fits(SinkTmdsFacts::new(true, true, true)));
265        // No scrambling support: refused at this rate.
266        assert!(!link.fits(SinkTmdsFacts::new(true, false, false)));
267        // A plain link on a sink that lost SCDC: no write any more.
268        let plain = TmdsLinkParams::choose(148_500, sink, source, TmdsPolicy::DEFAULT).unwrap();
269        assert!(!plain.fits(SinkTmdsFacts::NONE));
270        // The link compares its source facts and policy too.
271        let other = TmdsLinkParams::choose(
272            148_500,
273            sink,
274            source,
275            TmdsPolicy::DEFAULT.with_low_rate_scrambling(false),
276        )
277        .unwrap();
278        assert_ne!(plain, other);
279    }
280
281    const RATES: [u32; 9] = [
282        0,
283        25_175,
284        165_000,
285        339_999,
286        340_000,
287        340_001,
288        594_000,
289        600_000,
290        u32::MAX,
291    ];
292    const THRESHOLDS: [ScramblingThreshold; 2] = [
293        ScramblingThreshold::Above340,
294        ScramblingThreshold::AtOrAbove340,
295    ];
296    const BOOLS: [bool; 2] = [false, true];
297    const GATES: [TmdsConfigGate; 2] =
298        [TmdsConfigGate::AnyScdcSink, TmdsConfigGate::ScramblingSink];
299
300    /// Calls `f` with every combination of inputs over [`RATES`].
301    fn for_all(mut f: impl FnMut(u32, SinkTmdsFacts, SourceTmdsFacts, TmdsPolicy)) {
302        for rate in RATES {
303            for scdc in BOOLS {
304                for supported in BOOLS {
305                    for lte in BOOLS {
306                        for scr in BOOLS {
307                            for src in BOOLS {
308                                for pol in BOOLS {
309                                    for threshold in THRESHOLDS {
310                                        for gate in GATES {
311                                            f(
312                                                rate,
313                                                SinkTmdsFacts::new(scdc, supported, lte),
314                                                SourceTmdsFacts::new(src).with_scrambling(scr),
315                                                TmdsPolicy::DEFAULT
316                                                    .with_low_rate_scrambling(pol)
317                                                    .with_threshold(threshold)
318                                                    .with_tmds_config_gate(gate),
319                                            );
320                                        }
321                                    }
322                                }
323                            }
324                        }
325                    }
326                }
327            }
328        }
329    }
330
331    fn is_above(rate: u32, threshold: ScramblingThreshold) -> bool {
332        match threshold {
333            ScramblingThreshold::Above340 => rate > 340_000,
334            ScramblingThreshold::AtOrAbove340 => rate >= 340_000,
335        }
336    }
337
338    const ALL: SinkTmdsFacts = SinkTmdsFacts::new(true, true, true);
339    const CAN: SourceTmdsFacts = SourceTmdsFacts::new(true);
340    const AT_OR_ABOVE: TmdsPolicy =
341        TmdsPolicy::DEFAULT.with_threshold(ScramblingThreshold::AtOrAbove340);
342
343    // ---- Invariants over every combination ----
344
345    #[test]
346    fn errors_exactly_above_340_on_an_incapable_sink() {
347        for_all(|rate, sink, source, policy| {
348            let incapable = !(sink.scdc_present && sink.scrambling_supported && source.scrambling);
349            let result = TmdsLinkParams::choose(rate, sink, source, policy);
350            if rate > 340_000 && incapable {
351                assert_eq!(
352                    result,
353                    Err(ParamsError::ScramblingUnsupported {
354                        rate_khz: rate,
355                        no_scdc: !sink.scdc_present,
356                        no_scrambling_support: !sink.scrambling_supported,
357                        source_cannot_scramble: !source.scrambling,
358                    })
359                );
360            } else {
361                assert!(result.is_ok(), "{rate} {sink:?} {source:?} {policy:?}");
362            }
363        });
364    }
365
366    #[test]
367    fn link_is_consistent() {
368        for_all(|rate, sink, source, policy| {
369            let Ok(link) = TmdsLinkParams::choose(rate, sink, source, policy) else {
370                return;
371            };
372            assert_eq!(link.rate_khz(), rate);
373
374            let required = link.scrambling_decision() == ScramblingDecision::Required;
375            assert_eq!(link.clock_ratio() == ClockRatio::Div40, required);
376            assert_eq!(
377                required,
378                is_above(rate, policy.threshold)
379                    && sink.scdc_present
380                    && sink.scrambling_supported
381                    && source.scrambling
382            );
383            assert_eq!(
384                link.scrambling(),
385                !matches!(link.scrambling_decision(), ScramblingDecision::Off(_))
386            );
387
388            match link.sink_config() {
389                // `None` exactly when no write is due.
390                None => assert!(
391                    !sink.scdc_present
392                        || (!link.scrambling()
393                            && policy.tmds_config_gate == TmdsConfigGate::ScramblingSink
394                            && !sink.scrambling_supported)
395                ),
396                Some(config) => {
397                    assert!(sink.scdc_present);
398                    assert_eq!(config.scrambling_enable, link.scrambling());
399                    assert_eq!(
400                        config.high_tmds_clock_ratio,
401                        link.clock_ratio() == ClockRatio::Div40
402                    );
403                }
404            }
405        });
406    }
407
408    #[test]
409    fn every_reason_is_set_exactly_when_its_fact_blocks() {
410        for_all(|rate, sink, source, policy| {
411            let Ok(link) = TmdsLinkParams::choose(rate, sink, source, policy) else {
412                return;
413            };
414            if link.scrambling_decision() == ScramblingDecision::Required {
415                return;
416            }
417            let all_allow = sink.scdc_present
418                && sink.scrambling_supported
419                && sink.lte_340mcsc_scramble
420                && source.scrambling
421                && source.low_rate_scrambling
422                && policy.low_rate_scrambling;
423            match link.scrambling_decision() {
424                ScramblingDecision::LowRate => assert!(all_allow),
425                ScramblingDecision::Off(off) => {
426                    assert!(!all_allow);
427                    assert_eq!(off.no_scdc, !sink.scdc_present);
428                    assert_eq!(off.no_scrambling_support, !sink.scrambling_supported);
429                    assert_eq!(off.sink_does_not_declare, !sink.lte_340mcsc_scramble);
430                    assert_eq!(
431                        off.source_cannot,
432                        !(source.scrambling && source.low_rate_scrambling)
433                    );
434                    assert_eq!(off.policy_off, !policy.low_rate_scrambling);
435                }
436                ScramblingDecision::Required => unreachable!(),
437            }
438        });
439    }
440
441    // ---- The boundary ----
442
443    #[test]
444    fn exactly_340_000_follows_the_threshold() {
445        let link = TmdsLinkParams::choose(340_000, ALL, CAN, TmdsPolicy::DEFAULT).unwrap();
446        assert_eq!(link.clock_ratio(), ClockRatio::Div10);
447        assert_eq!(link.scrambling_decision(), ScramblingDecision::LowRate);
448
449        let link = TmdsLinkParams::choose(340_000, ALL, CAN, AT_OR_ABOVE).unwrap();
450        assert_eq!(link.clock_ratio(), ClockRatio::Div40);
451        assert_eq!(link.scrambling_decision(), ScramblingDecision::Required);
452    }
453
454    #[test]
455    fn rate_340_001_is_above_under_both_thresholds() {
456        for policy in [TmdsPolicy::DEFAULT, AT_OR_ABOVE] {
457            let link = TmdsLinkParams::choose(340_001, ALL, CAN, policy).unwrap();
458            assert_eq!(link.clock_ratio(), ClockRatio::Div40);
459            assert_eq!(link.sink_config(), Some(SinkTmdsConfig::new(true, true)));
460        }
461    }
462
463    #[test]
464    fn exactly_340_000_at_or_above_on_an_incapable_sink_falls_back() {
465        // No SCDC: the plain 1/10 link, nothing written, and the reason.
466        let link = TmdsLinkParams::choose(340_000, SinkTmdsFacts::NONE, CAN, AT_OR_ABOVE).unwrap();
467        assert_eq!(link.clock_ratio(), ClockRatio::Div10);
468        assert_eq!(link.sink_config(), None);
469        assert!(matches!(
470            link.scrambling_decision(),
471            ScramblingDecision::Off(off) if off.no_scdc
472        ));
473
474        // SCDC but no scrambling support, even with LTE_340Mcsc_scramble declared: the
475        // plain 1/10 link, the ratio cleared, and the reason.
476        let sink = SinkTmdsFacts::new(true, false, true);
477        let link = TmdsLinkParams::choose(340_000, sink, CAN, AT_OR_ABOVE).unwrap();
478        assert_eq!(link.clock_ratio(), ClockRatio::Div10);
479        assert_eq!(link.sink_config(), Some(SinkTmdsConfig::new(false, false)));
480        assert_eq!(
481            link.scrambling_decision(),
482            ScramblingDecision::Off(ScramblingOff {
483                no_scdc: false,
484                no_scrambling_support: true,
485                sink_does_not_declare: false,
486                source_cannot: false,
487                policy_off: false,
488            })
489        );
490    }
491
492    #[test]
493    fn low_rate_scrambling_needs_scrambling_support() {
494        // LTE_340Mcsc_scramble without a non-zero Max_TMDS_Character_Rate does not count:
495        // the sources take the low-rate fact from Linux's gated `scrambling.low_rates`.
496        let sink = SinkTmdsFacts::new(true, false, true);
497        let link = TmdsLinkParams::choose(297_000, sink, CAN, TmdsPolicy::DEFAULT).unwrap();
498        assert!(!link.scrambling());
499        assert_eq!(link.sink_config(), Some(SinkTmdsConfig::new(false, false)));
500    }
501
502    // ---- Named cases ----
503
504    #[test]
505    fn dvi_sink_gets_the_plain_link_with_every_reason() {
506        let link = TmdsLinkParams::choose(
507            148_500,
508            SinkTmdsFacts::NONE,
509            SourceTmdsFacts::new(false),
510            TmdsPolicy::DEFAULT.with_low_rate_scrambling(false),
511        )
512        .unwrap();
513        assert_eq!(link.clock_ratio(), ClockRatio::Div10);
514        assert_eq!(link.sink_config(), None);
515        assert_eq!(
516            link.scrambling_decision(),
517            ScramblingDecision::Off(ScramblingOff {
518                no_scdc: true,
519                no_scrambling_support: true,
520                sink_does_not_declare: true,
521                source_cannot: true,
522                policy_off: true,
523            })
524        );
525    }
526
527    #[test]
528    fn scdc_sink_below_threshold_gets_the_ratio_cleared() {
529        let sink = SinkTmdsFacts::new(true, true, false);
530        let link = TmdsLinkParams::choose(297_000, sink, CAN, TmdsPolicy::DEFAULT).unwrap();
531        assert_eq!(link.sink_config(), Some(SinkTmdsConfig::new(false, false)));
532    }
533
534    #[test]
535    fn low_rate_scrambling_writes_scrambling_enable_only() {
536        let link = TmdsLinkParams::choose(297_000, ALL, CAN, TmdsPolicy::DEFAULT).unwrap();
537        assert_eq!(link.scrambling_decision(), ScramblingDecision::LowRate);
538        assert_eq!(link.sink_config(), Some(SinkTmdsConfig::new(true, false)));
539    }
540
541    // ---- A source without a scrambler ----
542
543    const NO_SCRAMBLER: SourceTmdsFacts = SourceTmdsFacts::new(true).with_scrambling(false);
544
545    #[test]
546    fn source_without_scrambler_is_refused_above_340() {
547        assert_eq!(
548            TmdsLinkParams::choose(594_000, ALL, NO_SCRAMBLER, TmdsPolicy::DEFAULT),
549            Err(ParamsError::ScramblingUnsupported {
550                rate_khz: 594_000,
551                no_scdc: false,
552                no_scrambling_support: false,
553                source_cannot_scramble: true,
554            })
555        );
556    }
557
558    #[test]
559    fn source_without_scrambler_at_340_000_at_or_above_gets_the_plain_link() {
560        let link = TmdsLinkParams::choose(340_000, ALL, NO_SCRAMBLER, AT_OR_ABOVE).unwrap();
561        assert_eq!(link.clock_ratio(), ClockRatio::Div10);
562        assert!(matches!(
563            link.scrambling_decision(),
564            ScramblingDecision::Off(ScramblingOff {
565                source_cannot: true,
566                no_scdc: false,
567                no_scrambling_support: false,
568                ..
569            })
570        ));
571    }
572
573    #[test]
574    fn low_rate_scrambling_needs_the_scrambler_too() {
575        let link = TmdsLinkParams::choose(297_000, ALL, NO_SCRAMBLER, TmdsPolicy::DEFAULT).unwrap();
576        assert!(!link.scrambling());
577        assert!(matches!(
578            link.scrambling_decision(),
579            ScramblingDecision::Off(ScramblingOff {
580                source_cannot: true,
581                ..
582            })
583        ));
584    }
585
586    #[test]
587    fn source_facts_come_from_the_phy_capabilities() {
588        use hdmi_hal::phy::TmdsPhyCapabilities;
589        let none = SourceTmdsFacts::from(&TmdsPhyCapabilities::new(600_000));
590        assert!(!none.scrambling && !none.low_rate_scrambling);
591        // Low-rate scrambling without a scrambler counts as false.
592        let odd = SourceTmdsFacts::from(
593            &TmdsPhyCapabilities::new(600_000).with_low_rate_scrambling(true),
594        );
595        assert!(!odd.scrambling && !odd.low_rate_scrambling);
596        let full = SourceTmdsFacts::from(
597            &TmdsPhyCapabilities::new(600_000)
598                .with_scrambling(true)
599                .with_low_rate_scrambling(true),
600        );
601        assert_eq!(
602            full,
603            SourceTmdsFacts::new(true).with_max_character_rate_khz(600_000)
604        );
605    }
606
607    #[test]
608    fn new_keeps_a_scrambler_as_in_0_1() {
609        assert!(SourceTmdsFacts::new(false).scrambling);
610        assert_eq!(SourceTmdsFacts::new(false).max_character_rate_khz, u32::MAX);
611    }
612
613    // ---- The source's own maximum ----
614
615    #[test]
616    fn rate_above_the_source_maximum_is_refused_first() {
617        let source = CAN.with_max_character_rate_khz(340_000);
618        assert!(TmdsLinkParams::choose(340_000, ALL, source, TmdsPolicy::DEFAULT).is_ok());
619        // Refused even where the sink could not take the rate either: the source's limit
620        // comes first.
621        assert_eq!(
622            TmdsLinkParams::choose(594_000, SinkTmdsFacts::NONE, source, TmdsPolicy::DEFAULT),
623            Err(ParamsError::AboveSourceMaximum {
624                rate_khz: 594_000,
625                max_khz: 340_000,
626            })
627        );
628    }
629
630    #[test]
631    fn source_maximum_comes_from_the_phy_capabilities() {
632        use hdmi_hal::phy::TmdsPhyCapabilities;
633        let facts = SourceTmdsFacts::from(&TmdsPhyCapabilities::new(297_000));
634        assert_eq!(facts.max_character_rate_khz, 297_000);
635    }
636
637    #[test]
638    fn the_gate_decides_a_plain_links_write_on_a_sink_without_scrambling_support() {
639        // SCDC, but no scrambling support (Max_TMDS_Character_Rate 0).
640        let sink = SinkTmdsFacts::new(true, false, false);
641        let any = TmdsLinkParams::choose(148_500, sink, CAN, TmdsPolicy::DEFAULT).unwrap();
642        assert_eq!(any.sink_config(), Some(SinkTmdsConfig::new(false, false)));
643        let gated = TmdsPolicy::DEFAULT.with_tmds_config_gate(TmdsConfigGate::ScramblingSink);
644        let plain = TmdsLinkParams::choose(148_500, sink, CAN, gated).unwrap();
645        assert_eq!(plain.sink_config(), None);
646        // A sink that supports scrambling is written under either gate.
647        let supported = TmdsLinkParams::choose(148_500, ALL, CAN, gated).unwrap();
648        assert!(supported.sink_config().is_some());
649        assert_eq!(TmdsConfigGate::default(), TmdsConfigGate::AnyScdcSink);
650    }
651
652    #[test]
653    fn choose_is_const() {
654        const LINK: Result<TmdsLinkParams, ParamsError> =
655            TmdsLinkParams::choose(594_000, ALL, CAN, TmdsPolicy::DEFAULT);
656        const RATIO_IS_DIV40: bool = match LINK {
657            Ok(link) => matches!(link.clock_ratio(), ClockRatio::Div40),
658            Err(_) => false,
659        };
660        const { assert!(RATIO_IS_DIV40) };
661    }
662}