Skip to main content

display_types/
capabilities.rs

1/// A reference-counted, type-erased warning value.
2///
3/// Any type that implements [`core::error::Error`] + [`Send`] + [`Sync`] + `'static` can be
4/// wrapped in a `ParseWarning`. The built-in library variants use `EdidWarning`, but
5/// custom handlers may push their own error types without wrapping them in `EdidWarning`.
6///
7/// Using [`Arc`][crate::prelude::Arc] (rather than `Box`) means `ParseWarning` is
8/// [`Clone`], which lets warnings be copied from a parsed representation into
9/// [`DisplayCapabilities`] without consuming the parsed result.
10///
11/// To inspect a specific variant, use the inherent `downcast_ref` method available on
12/// `dyn core::error::Error + Send + Sync + 'static` in `std` builds:
13///
14/// ```text
15/// for w in caps.iter_warnings() {
16///     if let Some(ew) = (**w).downcast_ref::<EdidWarning>() { ... }
17/// }
18/// ```
19#[cfg(any(feature = "alloc", feature = "std"))]
20pub type ParseWarning = crate::prelude::Arc<dyn core::error::Error + Send + Sync + 'static>;
21
22/// Stereo viewing support decoded from DTD byte 17 bits 6, 5, and 0.
23#[non_exhaustive]
24#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum StereoMode {
27    /// Normal display; no stereo (bits 6–5 = `0b00`; bit 0 is don't-care).
28    #[default]
29    None,
30    /// Field-sequential stereo, right image when stereo sync = 1 (bits 6–5 = `0b01`, bit 0 = 0).
31    FieldSequentialRightFirst,
32    /// Field-sequential stereo, left image when stereo sync = 1 (bits 6–5 = `0b10`, bit 0 = 0).
33    FieldSequentialLeftFirst,
34    /// 2-way interleaved stereo, right image on even lines (bits 6–5 = `0b01`, bit 0 = 1).
35    TwoWayInterleavedRightEven,
36    /// 2-way interleaved stereo, left image on even lines (bits 6–5 = `0b10`, bit 0 = 1).
37    TwoWayInterleavedLeftEven,
38    /// 4-way interleaved stereo (bits 6–5 = `0b11`, bit 0 = 0).
39    FourWayInterleaved,
40    /// Side-by-side interleaved stereo (bits 6–5 = `0b11`, bit 0 = 1).
41    SideBySideInterleaved,
42}
43
44/// Sync signal definition decoded from DTD byte 17 bits 4–1.
45#[non_exhaustive]
46#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum SyncDefinition {
49    /// Analog composite sync (bit 4 = 0, bit 3 = 0).
50    AnalogComposite {
51        /// H-sync pulse present during V-sync (serrations).
52        serrations: bool,
53        /// Sync on all three RGB signals (`true`) or green only (`false`).
54        sync_on_all_rgb: bool,
55    },
56    /// Bipolar analog composite sync (bit 4 = 0, bit 3 = 1).
57    BipolarAnalogComposite {
58        /// H-sync pulse present during V-sync (serrations).
59        serrations: bool,
60        /// Sync on all three RGB signals (`true`) or green only (`false`).
61        sync_on_all_rgb: bool,
62    },
63    /// Digital composite sync on H-sync pin (bit 4 = 1, bit 3 = 0).
64    DigitalComposite {
65        /// H-sync pulse present during V-sync (serrations).
66        serrations: bool,
67        /// H-sync polarity outside V-sync: `true` = positive.
68        h_sync_positive: bool,
69    },
70    /// Digital separate sync (bit 4 = 1, bit 3 = 1).
71    DigitalSeparate {
72        /// V-sync polarity: `true` = positive.
73        v_sync_positive: bool,
74        /// H-sync polarity: `true` = positive.
75        h_sync_positive: bool,
76    },
77}
78
79/// A display video mode expressed as resolution, refresh rate, and scan type.
80///
81/// Use [`VideoMode::new`] to construct a mode with only identity fields (the common case
82/// for modes decoded from standard timing or SVD entries). Use
83/// [`VideoMode::with_detailed_timing`] to add the blanking-interval and signal fields
84/// available from a Detailed Timing Descriptor or equivalent.
85#[non_exhaustive]
86#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
87#[derive(Debug, Clone, PartialEq, Default)]
88pub struct VideoMode {
89    /// Horizontal resolution in pixels.
90    pub width: u16,
91    /// Vertical resolution in pixels.
92    pub height: u16,
93    /// Refresh rate in Hz.
94    pub refresh_rate: u8,
95    /// `true` for interlaced modes; `false` for progressive (the common case).
96    pub interlaced: bool,
97    /// Horizontal front porch in pixels (0 when not decoded from a DTD).
98    pub h_front_porch: u16,
99    /// Horizontal sync pulse width in pixels (0 when not decoded from a DTD).
100    pub h_sync_width: u16,
101    /// Vertical front porch in lines (0 when not decoded from a DTD).
102    pub v_front_porch: u16,
103    /// Vertical sync pulse width in lines (0 when not decoded from a DTD).
104    pub v_sync_width: u16,
105    /// Horizontal border width in pixels on each side of the active area (0 when not from a DTD).
106    pub h_border: u8,
107    /// Vertical border height in lines on each side of the active area (0 when not from a DTD).
108    pub v_border: u8,
109    /// Stereo viewing support (default [`StereoMode::None`] for non-DTD modes).
110    pub stereo: StereoMode,
111    /// Sync signal definition (`None` for non-DTD modes).
112    pub sync: Option<SyncDefinition>,
113}
114
115impl VideoMode {
116    /// Constructs a `VideoMode` with the given identity fields.
117    ///
118    /// All blanking-interval fields (`h_front_porch`, `h_sync_width`, `v_front_porch`,
119    /// `v_sync_width`, `h_border`, `v_border`) default to `0`, `stereo` defaults to
120    /// [`StereoMode::None`], and `sync` defaults to `None`. Use
121    /// [`with_detailed_timing`][Self::with_detailed_timing] to set those fields when
122    /// decoding from a Detailed Timing Descriptor.
123    pub fn new(width: u16, height: u16, refresh_rate: u8, interlaced: bool) -> Self {
124        Self {
125            width,
126            height,
127            refresh_rate,
128            interlaced,
129            ..Self::default()
130        }
131    }
132
133    /// Adds blanking-interval and signal fields decoded from a Detailed Timing Descriptor
134    /// or equivalent source, returning the updated mode.
135    ///
136    /// The 8-parameter count mirrors the DTD fields directly (EDID §3.10.3 / DisplayID §4.4).
137    #[allow(clippy::too_many_arguments)]
138    pub fn with_detailed_timing(
139        mut self,
140        h_front_porch: u16,
141        h_sync_width: u16,
142        v_front_porch: u16,
143        v_sync_width: u16,
144        h_border: u8,
145        v_border: u8,
146        stereo: StereoMode,
147        sync: Option<SyncDefinition>,
148    ) -> Self {
149        self.h_front_porch = h_front_porch;
150        self.h_sync_width = h_sync_width;
151        self.v_front_porch = v_front_porch;
152        self.v_sync_width = v_sync_width;
153        self.h_border = h_border;
154        self.v_border = v_border;
155        self.stereo = stereo;
156        self.sync = sync;
157        self
158    }
159}
160
161/// EDID specification version and revision, decoded from base block bytes 18–19.
162///
163/// Most displays in use report version 1 with revision 3 or 4.
164#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub struct EdidVersion {
167    /// EDID version number (byte 18). Always `1` for all current displays.
168    pub version: u8,
169    /// EDID revision number (byte 19).
170    pub revision: u8,
171}
172
173impl core::fmt::Display for EdidVersion {
174    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
175        write!(f, "{}.{}", self.version, self.revision)
176    }
177}
178
179/// Trait for typed data stored in [`DisplayCapabilities::extension_data`] by custom handlers.
180///
181/// A blanket implementation covers any type that is `Any + Debug + Send + Sync`, so consumers
182/// do not need to implement this trait manually — `#[derive(Debug)]` on a `Send + Sync` type
183/// is sufficient.
184#[cfg(any(feature = "alloc", feature = "std"))]
185pub trait ExtensionData: core::any::Any + core::fmt::Debug + Send + Sync {
186    /// Returns `self` as `&dyn Any` to enable downcasting.
187    fn as_any(&self) -> &dyn core::any::Any;
188}
189
190#[cfg(any(feature = "alloc", feature = "std"))]
191impl<T: core::any::Any + core::fmt::Debug + Send + Sync> ExtensionData for T {
192    fn as_any(&self) -> &dyn core::any::Any {
193        self
194    }
195}
196
197/// Consumer-facing display capability model produced by a display data parser.
198///
199/// All fields defined by the relevant specification are decoded and exposed here.
200/// No field is omitted because it appears obscure or unlikely to be needed — that
201/// judgement belongs to the consumer, not the library.
202///
203/// Fields are `Option` where the underlying data may be absent or undecodable.
204/// `None` means the value was not present or could not be reliably determined; it does
205/// not imply the field is unimportant. The library never invents or defaults data.
206#[non_exhaustive]
207#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
208#[derive(Debug, Clone, Default)]
209pub struct DisplayCapabilities {
210    /// Three-character PNP manufacturer ID (e.g. `GSM` for LG, `SAM` for Samsung).
211    pub manufacturer: Option<crate::manufacture::ManufacturerId>,
212    /// Manufacture date or model year.
213    pub manufacture_date: Option<crate::manufacture::ManufactureDate>,
214    /// EDID specification version and revision.
215    pub edid_version: Option<EdidVersion>,
216    /// Manufacturer-assigned product code.
217    pub product_code: Option<u16>,
218    /// Manufacturer-assigned serial number, if encoded numerically in the base block.
219    pub serial_number: Option<u32>,
220    /// Serial number string from the monitor serial number descriptor (`0xFF`), if present.
221    pub serial_number_string: Option<crate::manufacture::MonitorString>,
222    /// Human-readable display name from the monitor name descriptor, if present.
223    pub display_name: Option<crate::manufacture::MonitorString>,
224    /// Unspecified ASCII text strings from `0xFE` descriptors, in descriptor slot order.
225    ///
226    /// Up to four entries (one per descriptor slot). Each slot is `None` if the corresponding
227    /// descriptor was not a `0xFE` entry.
228    pub unspecified_text: [Option<crate::manufacture::MonitorString>; 4],
229    /// Additional white points from the `0xFB` descriptor.
230    ///
231    /// Up to two entries (the EDID `0xFB` descriptor has two fixed slots). Each slot is
232    /// `None` if the corresponding entry was unused (index byte `0x00`).
233    pub white_points: [Option<crate::color::WhitePoint>; 2],
234    /// `true` if the display uses a digital input interface.
235    pub digital: bool,
236    /// Color bit depth per primary channel.
237    /// `None` for analog displays or when the field is undefined or reserved.
238    pub color_bit_depth: Option<crate::color::ColorBitDepth>,
239    /// Physical display technology (e.g. TFT, OLED, PDP).
240    /// `None` when the Display Device Data Block is absent.
241    pub display_technology: Option<crate::panel::DisplayTechnology>,
242    /// Technology-specific sub-type code (raw, 0–15).
243    /// `None` when the Display Device Data Block is absent.
244    pub display_subtype: Option<u8>,
245    /// Panel operating mode (continuous or non-continuous refresh).
246    /// `None` when the Display Device Data Block is absent.
247    pub operating_mode: Option<crate::panel::OperatingMode>,
248    /// Backlight type.
249    /// `None` when the Display Device Data Block is absent.
250    pub backlight_type: Option<crate::panel::BacklightType>,
251    /// Whether the panel uses a Data Enable (DE) signal.
252    /// `None` when the Display Device Data Block is absent.
253    pub data_enable_used: Option<bool>,
254    /// Data Enable signal polarity: `true` = positive, `false` = negative.
255    /// Valid only when `data_enable_used` is `Some(true)`.
256    /// `None` when the Display Device Data Block is absent.
257    pub data_enable_positive: Option<bool>,
258    /// Native pixel format `(width_px, height_px)`.
259    /// `None` when the Display Device Data Block is absent or either dimension is zero.
260    pub native_pixels: Option<(u16, u16)>,
261    /// Panel aspect ratio encoded as `(AR − 1) × 100` (raw byte).
262    /// For example `77` represents approximately 16:9 (AR ≈ 1.77). `None` when the block is absent.
263    pub panel_aspect_ratio_100: Option<u8>,
264    /// Physical mounting orientation of the panel.
265    /// `None` when the Display Device Data Block is absent.
266    pub physical_orientation: Option<crate::panel::PhysicalOrientation>,
267    /// Panel rotation capability.
268    /// `None` when the Display Device Data Block is absent.
269    pub rotation_capability: Option<crate::panel::RotationCapability>,
270    /// Location of the zero (origin) pixel in the framebuffer.
271    /// `None` when the Display Device Data Block is absent.
272    pub zero_pixel_location: Option<crate::panel::ZeroPixelLocation>,
273    /// Fast-scan direction relative to H-sync.
274    /// `None` when the Display Device Data Block is absent.
275    pub scan_direction: Option<crate::panel::ScanDirection>,
276    /// Sub-pixel color filter arrangement.
277    /// `None` when the Display Device Data Block is absent.
278    pub subpixel_layout: Option<crate::panel::SubpixelLayout>,
279    /// Pixel pitch `(horizontal_hundredths_mm, vertical_hundredths_mm)` in 0.01 mm units.
280    /// `None` when the Display Device Data Block is absent or either pitch is zero.
281    pub pixel_pitch_hundredths_mm: Option<(u8, u8)>,
282    /// Pixel response time in milliseconds.
283    /// `None` when the Display Device Data Block is absent or the value is zero.
284    pub pixel_response_time_ms: Option<u8>,
285    /// Interface power sequencing timing parameters.
286    /// `None` when the Interface Power Sequencing Block is absent.
287    pub power_sequencing: Option<crate::panel::PowerSequencing>,
288    /// Display luminance transfer function.
289    /// `None` when the Transfer Characteristics Block is absent.
290    #[cfg(any(feature = "alloc", feature = "std"))]
291    pub transfer_characteristic: Option<crate::transfer::DisplayIdTransferCharacteristic>,
292    /// Physical display interface capabilities.
293    /// `None` when the Display Interface Data Block is absent.
294    pub display_id_interface: Option<crate::panel::DisplayIdInterface>,
295    /// Stereo display interface parameters.
296    /// `None` when the Stereo Display Interface Data Block is absent.
297    pub stereo_interface: Option<crate::panel::DisplayIdStereoInterface>,
298    /// Tiled display topology.
299    /// `None` when the Tiled Display Topology Data Block is absent.
300    pub tiled_topology: Option<crate::panel::DisplayIdTiledTopology>,
301    /// CIE xy chromaticity coordinates for the color primaries and white point.
302    pub chromaticity: crate::color::Chromaticity,
303    /// Display gamma. `None` if the display did not specify a gamma value.
304    pub gamma: Option<crate::color::DisplayGamma>,
305    /// Display feature support flags.
306    pub display_features: Option<crate::features::DisplayFeatureFlags>,
307    /// Supported color encoding formats. Only populated for EDID 1.4+ digital displays.
308    pub digital_color_encoding: Option<crate::color::DigitalColorEncoding>,
309    /// Color type for analog displays; `None` for the undefined value (`0b11`).
310    pub analog_color_type: Option<crate::color::AnalogColorType>,
311    /// Video interface type.
312    /// `None` for analog displays or when the field is undefined or reserved.
313    pub video_interface: Option<crate::input::VideoInterface>,
314    /// Analog sync and video white levels. Only populated for analog displays.
315    pub analog_sync_level: Option<crate::input::AnalogSyncLevel>,
316    /// Physical screen dimensions or aspect ratio.
317    /// `None` when both bytes are zero (undefined).
318    pub screen_size: Option<crate::screen::ScreenSize>,
319    /// Minimum supported vertical refresh rate in Hz.
320    pub min_v_rate: Option<u16>,
321    /// Maximum supported vertical refresh rate in Hz.
322    pub max_v_rate: Option<u16>,
323    /// Minimum supported horizontal scan rate in kHz.
324    pub min_h_rate_khz: Option<u16>,
325    /// Maximum supported horizontal scan rate in kHz.
326    pub max_h_rate_khz: Option<u16>,
327    /// Maximum pixel clock in MHz.
328    pub max_pixel_clock_mhz: Option<u16>,
329    /// Physical image area dimensions in millimetres `(width_mm, height_mm)`.
330    ///
331    /// More precise than [`screen_size`][Self::screen_size] (which is in cm).
332    /// `None` when all DTD image-size fields are zero.
333    pub preferred_image_size_mm: Option<(u16, u16)>,
334    /// Video timing formula reported in the display range limits descriptor.
335    pub timing_formula: Option<crate::timing::TimingFormula>,
336    /// DCM polynomial coefficients.
337    pub color_management: Option<crate::color::ColorManagementData>,
338    /// Video modes decoded from the display data.
339    #[cfg(any(feature = "alloc", feature = "std"))]
340    pub supported_modes: crate::prelude::Vec<VideoMode>,
341    /// Non-fatal conditions collected from the parser and all handlers.
342    ///
343    /// Not serialized — use a custom handler to map warnings to a serializable form.
344    #[cfg(any(feature = "alloc", feature = "std"))]
345    #[cfg_attr(feature = "serde", serde(skip))]
346    pub warnings: crate::prelude::Vec<ParseWarning>,
347    /// Typed data attached by extension handlers, keyed by extension tag byte.
348    ///
349    /// Uses a `Vec` of `(tag, data)` pairs rather than a `HashMap` so that this field is
350    /// available in `alloc`-only (no_std) builds. The number of distinct extension tags in
351    /// any real EDID is small enough that linear scan is negligible.
352    ///
353    /// Not serialized — use a custom handler to map this to a serializable form.
354    #[cfg(any(feature = "alloc", feature = "std"))]
355    #[cfg_attr(feature = "serde", serde(skip))]
356    pub extension_data: crate::prelude::Vec<(u8, crate::prelude::Arc<dyn ExtensionData>)>,
357}
358
359#[cfg(any(feature = "alloc", feature = "std"))]
360impl DisplayCapabilities {
361    /// Returns an iterator over all collected warnings.
362    pub fn iter_warnings(&self) -> impl Iterator<Item = &ParseWarning> {
363        self.warnings.iter()
364    }
365
366    /// Appends a warning, wrapping it in a [`ParseWarning`].
367    pub fn push_warning(&mut self, w: impl core::error::Error + Send + Sync + 'static) {
368        self.warnings.push(crate::prelude::Arc::new(w));
369    }
370
371    /// Store typed data from a handler, keyed by an extension tag.
372    /// Replaces any previously stored entry for the same tag.
373    pub fn set_extension_data<T: ExtensionData>(&mut self, tag: u8, data: T) {
374        if let Some(entry) = self.extension_data.iter_mut().find(|(t, _)| *t == tag) {
375            entry.1 = crate::prelude::Arc::new(data);
376        } else {
377            self.extension_data
378                .push((tag, crate::prelude::Arc::new(data)));
379        }
380    }
381
382    /// Retrieve typed data previously stored by a handler for the given tag.
383    /// Returns `None` if no data is stored for the tag or the type does not match.
384    pub fn get_extension_data<T: core::any::Any>(&self, tag: u8) -> Option<&T> {
385        self.extension_data
386            .iter()
387            .find(|(t, _)| *t == tag)
388            // `**data` deref-chains through `&` then through Arc's Deref to reach
389            // `dyn ExtensionData`, forcing vtable dispatch for `as_any()`.
390            // Calling `.as_any()` on `&Arc<dyn ExtensionData>` would hit the blanket
391            // `ExtensionData` impl for Arc itself and return the wrong TypeId.
392            .and_then(|(_, data)| (**data).as_any().downcast_ref::<T>())
393    }
394}