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