liboptic_edid 0.1.0

Parses EDIDs from raw bytes (in 100% Rust)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use bitvec::{order::Lsb0, slice::BitSlice};

use crate::prelude::internal::*;

/// Parses out some basic info about the display.
#[tracing::instrument]
pub(super) fn parse(input: &[u8]) -> Result<BasicDisplayInfo, EdidError> {
    let input_definition = video_input_definition(input[0x14])?;
    let screen_size_or_aspect_ratio = size_or_ratio(input);
    let reported_gamma = gamma(input);
    let feature_support = feature_support(input);

    Ok(BasicDisplayInfo {
        input_definition,
        screen_size_or_aspect_ratio,
        reported_gamma,
        feature_support,
    })
}

#[tracing::instrument]
fn video_input_definition(byte: u8) -> Result<VideoSignalInterface, EdidError> {
    // using lsb to keep the bit numbering consistent.
    let bits: &BitSlice<u8, Lsb0> = BitSlice::from_element(&byte);

    fn digital(bits: &BitSlice<u8, Lsb0>) -> Result<VideoSignalInterface, EdidError> {
        let color_bit_depth = match (bits[6], bits[5], bits[4]) {
            (false, false, false) => ColorBitDepth::Undefined,
            (false, false, true) => ColorBitDepth::D6Bits,
            (false, true, false) => ColorBitDepth::D8Bits,
            (false, true, true) => ColorBitDepth::D10Bits,
            (true, false, false) => ColorBitDepth::D12Bits,
            (true, false, true) => ColorBitDepth::D14Bits,
            (true, true, false) => ColorBitDepth::D16Bits,
            (true, true, true) => ColorBitDepth::Reserved,
        };

        // digital interface
        //
        // check if it's even supported
        let digital_interface = if !bits[3] && !bits[2] && !bits[1] && !bits[0] {
            tracing::debug!("digitial interface is not reported.");
            None
        } else {
            let di_bits = [bits[3], bits[2], bits[1], bits[0]];
            Some(match di_bits {
                [false, false, false, true] => SupportedVideoInterface::Dvi,
                [false, false, true, false] => SupportedVideoInterface::HdmiA,
                [false, false, true, true] => SupportedVideoInterface::HdmiB,
                [false, true, false, false] => SupportedVideoInterface::Mddi,
                [false, true, false, true] => SupportedVideoInterface::DisplayPort,
                reserved => {
                    tracing::error!("Got an unexpected digital video interface standard bit layout: `{reserved:#?}`");
                    return Err(EdidError::BasicInfoBadInterface(di_bits));
                }
            })
        };

        Ok(VideoSignalInterface::Digital {
            color_bit_depth,
            supported_interface: digital_interface,
        })
    }

    fn analog(bits: &BitSlice<u8, Lsb0>) -> VideoSignalInterface {
        // check level standard
        let signal_level_standard = match (bits[6], bits[5]) {
            (false, false) => analog::SignalLevelStandard::_0700S_0300L_1000T,
            (false, true) => analog::SignalLevelStandard::_0714S_0286L_1000T,
            (true, false) => analog::SignalLevelStandard::_1000S_0400L_1400T,
            (true, true) => analog::SignalLevelStandard::_0700S_0000L_0700T,
        };

        // video setup
        let video_setup = if bits[4] {
            analog::VideoSetup::B2BOrPedestal
        } else {
            analog::VideoSetup::BlackLevel
        };

        // sync types
        let sync_types = analog::SyncTypes {
            separate_sync_h_and_v: bits[3],
            composite_sync_horizontal: bits[2],
            composite_sync_green_video: bits[1],
        };

        let serrations = bits[0];

        VideoSignalInterface::Analog {
            signal_level_standard,
            video_setup,
            sync_types,
            serrations,
        }
    }

    // 0 if analog, 1 if digital
    if bits[7] {
        digital(bits)
    } else {
        Ok(analog(bits))
    }
}

#[tracing::instrument(skip_all)]
fn size_or_ratio(input: &[u8]) -> Option<SizeOrRatio> {
    match (input[0x15], input[0x16]) {
        // when both are 0x00, the screen's size isn't given or may be dynamic
        (0x00, 0x00) => None,

        // if vertical is 0x00, then horizontal is the landscape aspect ratio
        (horizontal, 0x00) => {
            tracing::debug!("landscape aspect ratio, given: `0x{horizontal:x}` (`{horizontal}`)");
            let (hoz, vert) = make_ratio(horizontal)?;

            Some(SizeOrRatio::AspectRatio {
                horizontal: hoz,
                vertical: vert,
            })
        }

        // now if horizontal is 0x00, we know to expect portrait orientation
        (0x00, vertical) => {
            tracing::debug!("portrait aspect ratio, given: `0x{vertical:x}` (`{vertical}`)");
            let (vert, hoz) = make_ratio(vertical)?;

            Some(SizeOrRatio::AspectRatio {
                horizontal: hoz,
                vertical: vert,
            })
        }

        // both are greater than zero, so we've got two cm counts
        (horizontal_cm, vertical_cm) => Some(SizeOrRatio::ScreenSize {
            vertical_cm,
            horizontal_cm,
        }),
    }
}

/// Makes an aspect ratio with the rounded EDID val: `?.xyz` => xyz_u8 (`ar)`.
///
/// To get landscape, pattern match the return value as `(hoz, vert)`. For
/// portrait, it's `(vert, hoz)`.
#[tracing::instrument]
fn make_ratio(ar: u8) -> Option<(u16, u16)> {
    // note: these values are calculated by dividing one side by the other,
    // then rounding to three decimal places.
    //
    // that works because `ar` is just those remaining decimal digits.
    // however, that also limits the ratio from (1:1 to 3.55:1), which
    // doesn't account for loooong displays.
    //
    // in addition, 1:1 (square) displays are not representable.
    //
    // i believe this is a limitation of the standard. (hopefully fixed in
    // displayid!)
    Some(match ar {
        0x00 => unreachable!(),
        0x4F => (16, 9),
        0x3D => (16, 10),
        0x22 => (4, 3),
        0x1A => (5, 4),
        0x05 => (3, 2),
        134 => (21, 9),
        _ => {
            if ar == 255 {
                tracing::warn!(
                    "Attempted to find EDID aspect ratio for monitor with ratio at 3.55:1.\
                Note that this display may have a different aspect ratio."
                );
            }

            let horiz_ar = 100 + (ar as u16);
            let frac = num_rational::Ratio::<u16>::new(horiz_ar, 100_u16);
            (*frac.numer(), *frac.denom())
        }
    })
}

/// Gets the gamma value from the given input stream.
///
/// Note that if this is `None`, the display should provide an extension
/// containing the value.
#[tracing::instrument(skip_all)]
fn gamma(input: &[u8]) -> Option<Decimal> {
    let byte = input[0x17];
    tracing::debug!("Got byte: 0x{byte:x}");

    if byte == 0xFF {
        tracing::info!("Reported None. An extension with the gamma value should follow...");
        None
    } else {
        if byte == 0x00 {
            tracing::warn!(
                "EDID 1.4 does not provide a defintion for `gamma: 0x00`, \
                but this display is using that. This may result in an inaccurate \
                answer."
            );
        }

        // reverse from the standard: byte = (GAMMA x 100) – 100
        Some((Decimal::from(byte) + Decimal::from(100)) / Decimal::from(100))
    }
}

#[tracing::instrument]
fn feature_support(input: &[u8]) -> FeatureSupport {
    // again, using `Lsb0` despite standard being Msb0.
    //
    // this lets me use their numbering
    let bits: &BitSlice<u8, Lsb0> = BitSlice::from_element(&input[0x18]);

    // build the power management (i.e. bools)
    let power_management = PowerManagement {
        standby: bits[7],
        suspend: bits[6],
        active_off: bits[5],
    };

    // get color based on if we're analog/digital...
    let color_support = if BitSlice::<u8, Lsb0>::from_element(&input[0x14])[7] {
        // digital gets a color encoding!
        let formats = match (bits[4], bits[3]) {
            (false, false) => ColorEncodingFormats::Rgb444,
            (false, true) => ColorEncodingFormats::Rgb444_YCrCb444,
            (true, false) => ColorEncodingFormats::Rgb444_YCrCb422,
            (true, true) => ColorEncodingFormats::Rgb444_YCrCb444_YCrCb422,
        };

        ColorSupport::EncodingFormats(formats)
    } else {
        // if we're analog, just check the color type.
        let ty = match (bits[4], bits[3]) {
            (false, false) => ColorType::MonochromeOrGrayscale,
            (false, true) => ColorType::RgbColor,
            (true, false) => ColorType::NonRgbColor,
            (true, true) => ColorType::Undefined,
        };

        ColorSupport::Type(ty)
    };

    // other feature support flags
    let srgb_std = bits[2];
    let says_pixel_format_and_refresh = bits[1];
    let is_continuous_freq = bits[0];

    FeatureSupport {
        power_management,
        color_support,
        srgb_std,
        says_pixel_format_and_refresh,
        is_continuous_freq,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::{
        parser::{
            basic_info::make_ratio,
            util::{edid_by_filename, logger},
        },
        structures::basic_info::{
            feature_support::{
                ColorEncodingFormats, ColorSupport, FeatureSupport, PowerManagement,
            },
            vsi::{
                digital::{ColorBitDepth, SupportedVideoInterface},
                VideoSignalInterface,
            },
            SizeOrRatio,
        },
    };

    use super::BasicDisplayInfo;

    #[test]
    fn dell_s2417dg_vsi() {
        logger();
        let input = crate::prelude::internal::raw_edid_by_filename("dell_s2417dg.raw.input");
        let got = super::video_input_definition(input[0x14]).unwrap();

        let expected = VideoSignalInterface::Digital {
            color_bit_depth: ColorBitDepth::D8Bits,
            supported_interface: Some(SupportedVideoInterface::DisplayPort),
        };

        assert_eq!(got, expected);
    }

    #[test]
    fn that_guys_laptop_vsi() {
        logger();
        let input = crate::prelude::internal::edid_by_filename("1.input");
        let got = super::video_input_definition(input[0x14]).unwrap();

        let expected = VideoSignalInterface::Digital {
            color_bit_depth: ColorBitDepth::D6Bits,
            supported_interface: None,
        };

        assert_eq!(got, expected);
    }

    #[test]
    fn dell_s2417dg_sizeratio() {
        logger();
        let input = crate::prelude::internal::raw_edid_by_filename("dell_s2417dg.raw.input");
        let got = super::size_or_ratio(&input).unwrap();

        let expected = SizeOrRatio::ScreenSize {
            vertical_cm: 30,
            horizontal_cm: 53,
        };

        assert_eq!(got, expected);
    }

    #[test]
    fn that_guys_laptop_sizeratio() {
        logger();
        let input = crate::prelude::internal::edid_by_filename("1.input");
        let got = super::size_or_ratio(&input).unwrap();

        let expected = SizeOrRatio::ScreenSize {
            vertical_cm: 17,
            horizontal_cm: 29,
        };

        assert_eq!(got, expected);
    }

    #[test]
    fn display_w_aspect_ratio() {
        logger();
        let input = edid_by_filename("linuxhw_edid_Digital_BOE_BOE07AF_BD22D8FDF96B.input");
        let got = super::size_or_ratio(&input).unwrap();

        let expected = SizeOrRatio::AspectRatio {
            horizontal: 16,
            vertical: 9,
        };

        assert_eq!(got, expected);
    }

    #[test]
    fn lotta_aspect_ratios() {
        logger();
        let _get_ar_val = |x: u8, y: u8| ((x as f32 / y as f32) * 100.0) - 99.0;
        // panic!("{}", _get_ar_val(33, 23));

        assert_eq!(make_ratio(79_u8), Some((16, 9)));
        assert_eq!(make_ratio(61_u8), Some((16, 10)));
        assert_eq!(make_ratio(34_u8), Some((4, 3)));
        assert_eq!(make_ratio(26_u8), Some((5, 4)));
        assert_eq!(make_ratio(5_u8), Some((3, 2)));
        assert_eq!(make_ratio(134_u8), Some((21, 9)));

        // some weird ones i pulled outta my ass
        assert_eq!(make_ratio(16_u8), Some((29, 25)));
        assert_eq!(make_ratio(45_u8), Some((29, 20)));
        assert_eq!(make_ratio(255_u8), Some((71, 20))); // i would so buy this
    }

    #[test]
    fn dell_s2417dg_gamma() {
        logger();
        let input = crate::prelude::internal::raw_edid_by_filename("dell_s2417dg.raw.input");
        let got = super::gamma(&input).unwrap();
        let expected = dec!(2.20);

        assert_eq!(got, expected);
    }

    #[test]
    fn that_guys_laptop_gamma() {
        logger();
        let input = crate::prelude::internal::edid_by_filename("1.input");
        let got = super::gamma(&input).unwrap();
        let expected = dec!(2.20);

        assert_eq!(got, expected);
    }

    #[test]
    fn _93d328459ff6_gamma() {
        logger();
        let input = crate::prelude::internal::edid_by_filename(
            "linuxhw_edid_EDID_Digital_Sony_SNY05FA_93D328459FF6.input",
        );
        let got = super::gamma(&input).unwrap();
        let expected = dec!(1.0);

        assert_eq!(got, expected);
    }

    #[test]
    fn dell_s2417dg_feature_support() {
        logger();
        let input = crate::prelude::internal::raw_edid_by_filename("dell_s2417dg.raw.input");

        let got = super::feature_support(&input);
        let expected = FeatureSupport {
            power_management: PowerManagement {
                standby: false,
                suspend: false,
                active_off: false,
            },
            color_support: ColorSupport::EncodingFormats(ColorEncodingFormats::Rgb444),
            srgb_std: true,
            says_pixel_format_and_refresh: true,
            is_continuous_freq: false,
        };

        assert_eq!(got, expected);
    }

    #[test]
    fn that_guys_laptop_feature_support() {
        logger();
        let input = crate::prelude::internal::edid_by_filename("1.input");

        let got = super::feature_support(&input);
        let expected = FeatureSupport {
            power_management: PowerManagement {
                standby: false,
                suspend: false,
                active_off: false,
            },
            color_support: ColorSupport::EncodingFormats(ColorEncodingFormats::Rgb444),
            srgb_std: false,
            says_pixel_format_and_refresh: true,
            is_continuous_freq: false,
        };

        assert_eq!(got, expected);
    }

    #[test]
    fn _93d328459ff6_feature_support() {
        logger();
        let input = crate::prelude::internal::edid_by_filename(
            "linuxhw_edid_EDID_Digital_Sony_SNY05FA_93D328459FF6.input",
        );

        let got = super::feature_support(&input);
        let expected = FeatureSupport {
            power_management: PowerManagement {
                standby: true,
                suspend: true,
                active_off: true,
            },
            color_support: ColorSupport::EncodingFormats(ColorEncodingFormats::Rgb444_YCrCb444),
            srgb_std: false,
            says_pixel_format_and_refresh: true,
            is_continuous_freq: false,
        };

        assert_eq!(got, expected);
    }

    /// if this passes, we're chillin
    #[test]
    fn _2c47316eff13_all_basic_info() {
        logger();
        let input = crate::prelude::internal::edid_by_filename(
            "linuxhw_edid_EDID_Digital_Samsung_SAM02E3_2C47316EFF13.input",
        );

        let got = super::parse(&input).unwrap();
        let expected = BasicDisplayInfo {
            // this is gonna be a long one lol
            input_definition: VideoSignalInterface::Digital {
                color_bit_depth: ColorBitDepth::D8Bits,
                supported_interface: Some(SupportedVideoInterface::DisplayPort),
            },
            screen_size_or_aspect_ratio: Some(SizeOrRatio::ScreenSize {
                horizontal_cm: 37,
                vertical_cm: 23,
            }),
            reported_gamma: Some(dec!(2.35)),
            feature_support: FeatureSupport {
                power_management: PowerManagement {
                    standby: false,
                    suspend: false,
                    active_off: true,
                },
                srgb_std: false,
                color_support: ColorSupport::EncodingFormats(ColorEncodingFormats::Rgb444),
                says_pixel_format_and_refresh: true,
                is_continuous_freq: false,
            },
        };

        assert_eq!(got, expected);
    }
}