webrtc-constraints 0.1.0

A pure Rust implementation of WebRTC Media Constraints API
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use crate::{MediaTrackSetting, ResolvedMediaTrackConstraint};

use super::FitnessDistance;

/// An error indicating a rejected fitness distance computation,
/// likely caused by a mismatched yet required constraint.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct SettingFitnessDistanceError {
    /// The kind of the error (e.g. missing value, mismatching value, …).
    pub kind: SettingFitnessDistanceErrorKind,
    /// The required constraint value.
    pub constraint: String,
    /// The offending setting value.
    pub setting: Option<String>,
}

/// The kind of the error (e.g. missing value, mismatching value, …).
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum SettingFitnessDistanceErrorKind {
    /// Settings value is missing.
    Missing,
    /// Settings value is a mismatch.
    Mismatch,
    /// Settings value is too small.
    TooSmall,
    /// Settings value is too large.
    TooLarge,
}

impl<'a> FitnessDistance<Option<&'a MediaTrackSetting>> for ResolvedMediaTrackConstraint {
    type Error = SettingFitnessDistanceError;

    fn fitness_distance(&self, setting: Option<&'a MediaTrackSetting>) -> Result<f64, Self::Error> {
        type Setting = MediaTrackSetting;
        type Constraint = ResolvedMediaTrackConstraint;

        let setting = match setting {
            Some(setting) => setting,
            None => {
                return if self.is_required() {
                    Err(Self::Error {
                        kind: SettingFitnessDistanceErrorKind::Missing,
                        constraint: format!("{}", self.to_required_only()),
                        setting: None,
                    })
                } else {
                    Ok(1.0)
                }
            }
        };

        let result = match (self, setting) {
            // Empty constraint:
            (ResolvedMediaTrackConstraint::Empty(constraint), setting) => {
                constraint.fitness_distance(Some(setting))
            }

            // Boolean constraint:
            (Constraint::Bool(constraint), Setting::Bool(setting)) => {
                constraint.fitness_distance(Some(setting))
            }
            (Constraint::Bool(constraint), Setting::Integer(setting)) => {
                constraint.fitness_distance(Some(setting))
            }
            (Constraint::Bool(constraint), Setting::Float(setting)) => {
                constraint.fitness_distance(Some(setting))
            }
            (Constraint::Bool(constraint), Setting::String(setting)) => {
                constraint.fitness_distance(Some(setting))
            }

            // Integer constraint:
            (Constraint::IntegerRange(_constraint), Setting::Bool(_setting)) => Ok(0.0),
            (Constraint::IntegerRange(constraint), Setting::Integer(setting)) => {
                constraint.fitness_distance(Some(setting))
            }
            (Constraint::IntegerRange(constraint), Setting::Float(setting)) => {
                constraint.fitness_distance(Some(setting))
            }
            (Constraint::IntegerRange(_constraint), Setting::String(_setting)) => Ok(0.0),

            // Float constraint:
            (Constraint::FloatRange(_constraint), Setting::Bool(_setting)) => Ok(0.0),
            (Constraint::FloatRange(constraint), Setting::Integer(setting)) => {
                constraint.fitness_distance(Some(setting))
            }
            (Constraint::FloatRange(constraint), Setting::Float(setting)) => {
                constraint.fitness_distance(Some(setting))
            }
            (Constraint::FloatRange(_constraint), Setting::String(_setting)) => Ok(0.0),

            // String constraint:
            (Constraint::String(_constraint), Setting::Bool(_setting)) => Ok(0.0),
            (Constraint::String(_constraint), Setting::Integer(_setting)) => Ok(0.0),
            (Constraint::String(_constraint), Setting::Float(_setting)) => Ok(0.0),
            (Constraint::String(constraint), Setting::String(setting)) => {
                constraint.fitness_distance(Some(setting))
            }

            // String sequence constraint:
            (Constraint::StringSequence(_constraint), Setting::Bool(_setting)) => Ok(0.0),
            (Constraint::StringSequence(_constraint), Setting::Integer(_setting)) => Ok(0.0),
            (Constraint::StringSequence(_constraint), Setting::Float(_setting)) => Ok(0.0),
            (Constraint::StringSequence(constraint), Setting::String(setting)) => {
                constraint.fitness_distance(Some(setting))
            }
        };

        #[cfg(debug_assertions)]
        if let Ok(fitness_distance) = result {
            debug_assert!({ fitness_distance.is_finite() });
        }

        result
    }
}

#[cfg(test)]
mod tests {
    use crate::{constraint::EmptyConstraint, MediaTrackSetting, ResolvedMediaTrackConstraint};

    use super::*;

    #[test]
    fn empty_constraint() {
        // As per step 1 of the `SelectSettings` algorithm from the W3C spec:
        // <https://www.w3.org/TR/mediacapture-streams/#dfn-selectsettings>
        //
        // > Each constraint specifies one or more values (or a range of values) for its property.
        // > A property MAY appear more than once in the list of 'advanced' ConstraintSets.
        // > If an empty list has been given as the value for a constraint,
        // > it MUST be interpreted as if the constraint were not specified
        // > (in other words, an empty constraint == no constraint).
        let constraint = ResolvedMediaTrackConstraint::Empty(EmptyConstraint {});

        let settings = [
            MediaTrackSetting::Bool(true),
            MediaTrackSetting::Integer(42),
            MediaTrackSetting::Float(4.2),
            MediaTrackSetting::String("string".to_owned()),
        ];

        let expected = 0.0;

        for setting in settings {
            let actual = constraint.fitness_distance(Some(&setting)).unwrap();

            assert_eq!(actual, expected);
        }
    }

    mod bool_constraint {
        use crate::ResolvedValueConstraint;

        use super::*;

        #[test]
        fn bool_setting() {
            // As per step 8 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > For all string, enum and boolean constraints
            // > (e.g. deviceId, groupId, facingMode, resizeMode, echoCancellation),
            // > the fitness distance is the result of the formula:
            // >
            // > ```
            // > (actual == ideal) ? 0 : 1
            // > ```

            let scenarios = [(false, false), (false, true), (true, false), (true, true)];

            for (constraint_value, setting_value) in scenarios {
                let constraint = ResolvedMediaTrackConstraint::Bool(ResolvedValueConstraint {
                    exact: None,
                    ideal: Some(constraint_value),
                });

                let setting = MediaTrackSetting::Bool(setting_value);

                let actual = constraint.fitness_distance(Some(&setting)).unwrap();

                let expected = if constraint_value == setting_value {
                    0.0
                } else {
                    1.0
                };

                assert_eq!(actual, expected);
            }
        }

        #[test]
        fn non_bool_settings() {
            // As per step 4 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > If constraintValue is a boolean, but the constrainable property is not,
            // > then the fitness distance is based on whether the settings dictionary's
            // > constraintName member exists or not, from the formula:
            // >
            // > ```
            // > (constraintValue == exists) ? 0 : 1
            // > ```

            let settings = [
                MediaTrackSetting::Integer(42),
                MediaTrackSetting::Float(4.2),
                MediaTrackSetting::String("string".to_owned()),
            ];

            let scenarios = [(false, false), (false, true), (true, false), (true, true)];

            for (constraint_value, setting_value) in scenarios {
                let constraint = ResolvedMediaTrackConstraint::Bool(ResolvedValueConstraint {
                    exact: None,
                    ideal: Some(constraint_value),
                });

                for setting in settings.iter() {
                    // TODO: Replace `if { Some(_) } else { None }` with `.then_some(_)`
                    // once MSRV has passed 1.62.0:
                    let setting = if setting_value { Some(setting) } else { None };
                    let actual = constraint.fitness_distance(setting).unwrap();

                    let expected = if setting_value { 0.0 } else { 1.0 };

                    assert_eq!(actual, expected);
                }
            }
        }
    }

    mod numeric_constraint {
        use crate::ResolvedValueRangeConstraint;

        use super::*;

        #[test]
        fn missing_settings() {
            // As per step 5 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > If the settings dictionary's constraintName member does not exist,
            // > the fitness distance is 1.

            let constraints = [
                ResolvedMediaTrackConstraint::IntegerRange(ResolvedValueRangeConstraint {
                    exact: None,
                    ideal: Some(42),
                    min: None,
                    max: None,
                }),
                ResolvedMediaTrackConstraint::FloatRange(ResolvedValueRangeConstraint {
                    exact: None,
                    ideal: Some(42.0),
                    min: None,
                    max: None,
                }),
            ];

            for constraint in constraints {
                let actual = constraint.fitness_distance(None).unwrap();

                let expected = 1.0;

                assert_eq!(actual, expected);
            }
        }

        #[test]
        fn compatible_settings() {
            // As per step 7 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > For all positive numeric constraints
            // > (such as height, width, frameRate, aspectRatio, sampleRate and sampleSize),
            // > the fitness distance is the result of the formula
            // >
            // > ```
            // > (actual == ideal) ? 0 : |actual - ideal| / max(|actual|, |ideal|)
            // > ```

            let settings = [
                MediaTrackSetting::Integer(21),
                MediaTrackSetting::Float(21.0),
            ];

            let constraints = [
                ResolvedMediaTrackConstraint::IntegerRange(ResolvedValueRangeConstraint {
                    exact: None,
                    ideal: Some(42),
                    min: None,
                    max: None,
                }),
                ResolvedMediaTrackConstraint::FloatRange(ResolvedValueRangeConstraint {
                    exact: None,
                    ideal: Some(42.0),
                    min: None,
                    max: None,
                }),
            ];

            for constraint in constraints {
                for setting in settings.iter() {
                    let actual = constraint.fitness_distance(Some(setting)).unwrap();

                    let expected = 0.5;

                    assert_eq!(actual, expected);
                }
            }
        }

        #[test]
        fn incompatible_settings() {
            // As per step 3 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > If the constraint does not apply for this type of object, the fitness distance is 0
            // > (that is, the constraint does not influence the fitness distance).

            let settings = [
                MediaTrackSetting::Bool(true),
                MediaTrackSetting::String("string".to_owned()),
            ];

            let constraints = [
                ResolvedMediaTrackConstraint::IntegerRange(ResolvedValueRangeConstraint {
                    exact: None,
                    ideal: Some(42),
                    min: None,
                    max: None,
                }),
                ResolvedMediaTrackConstraint::FloatRange(ResolvedValueRangeConstraint {
                    exact: None,
                    ideal: Some(42.0),
                    min: None,
                    max: None,
                }),
            ];

            for constraint in constraints {
                for setting in settings.iter() {
                    let actual = constraint.fitness_distance(Some(setting)).unwrap();

                    let expected = 0.0;

                    println!("constraint: {:?}", constraint);
                    println!("setting: {:?}", setting);
                    println!("actual: {:?}", actual);
                    println!("expected: {:?}", expected);

                    assert_eq!(actual, expected);
                }
            }
        }
    }

    mod string_constraint {
        use crate::ResolvedValueConstraint;

        use super::*;

        #[test]
        fn missing_settings() {
            // As per step 5 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > If the settings dictionary's constraintName member does not exist,
            // > the fitness distance is 1.

            let constraint = ResolvedMediaTrackConstraint::String(ResolvedValueConstraint {
                exact: None,
                ideal: Some("constraint".to_owned()),
            });

            let actual = constraint.fitness_distance(None).unwrap();

            let expected = 1.0;

            assert_eq!(actual, expected);
        }

        #[test]
        fn compatible_settings() {
            // As per step 8 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > For all string, enum and boolean constraints
            // > (e.g. deviceId, groupId, facingMode, resizeMode, echoCancellation),
            // > the fitness distance is the result of the formula:
            // >
            // > ```
            // > (actual == ideal) ? 0 : 1
            // > ```

            let constraint = ResolvedMediaTrackConstraint::String(ResolvedValueConstraint {
                exact: None,
                ideal: Some("constraint".to_owned()),
            });

            let settings = [MediaTrackSetting::String("setting".to_owned())];

            for setting in settings {
                let actual = constraint.fitness_distance(Some(&setting)).unwrap();

                let expected = 1.0;

                assert_eq!(actual, expected);
            }
        }

        #[test]
        fn incompatible_settings() {
            // As per step 3 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > If the constraint does not apply for this type of object, the fitness distance is 0
            // > (that is, the constraint does not influence the fitness distance).

            let constraint = ResolvedMediaTrackConstraint::String(ResolvedValueConstraint {
                exact: None,
                ideal: Some("string".to_owned()),
            });

            let settings = [
                MediaTrackSetting::Bool(true),
                MediaTrackSetting::Integer(42),
                MediaTrackSetting::Float(4.2),
            ];

            for setting in settings {
                let actual = constraint.fitness_distance(Some(&setting)).unwrap();

                let expected = 0.0;

                println!("constraint: {:?}", constraint);
                println!("setting: {:?}", setting);
                println!("actual: {:?}", actual);
                println!("expected: {:?}", expected);

                assert_eq!(actual, expected);
            }
        }
    }

    mod string_sequence_constraint {
        use crate::ResolvedValueSequenceConstraint;

        use super::*;

        #[test]
        fn missing_settings() {
            // As per step 5 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > If the settings dictionary's constraintName member does not exist,
            // > the fitness distance is 1.

            let constraint =
                ResolvedMediaTrackConstraint::StringSequence(ResolvedValueSequenceConstraint {
                    exact: None,
                    ideal: Some(vec!["constraint".to_owned()]),
                });

            let actual = constraint.fitness_distance(None).unwrap();

            let expected = 1.0;

            assert_eq!(actual, expected);
        }

        #[test]
        fn compatible_settings() {
            // As per step 8 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > For all string, enum and boolean constraints
            // > (e.g. deviceId, groupId, facingMode, resizeMode, echoCancellation),
            // > the fitness distance is the result of the formula:
            // >
            // > ```
            // > (actual == ideal) ? 0 : 1
            // > ```
            //
            // As well as the preliminary definition:
            //
            // > For string valued constraints, we define "==" below to be true if one of the
            // > values in the sequence is exactly the same as the value being compared against.

            let constraint =
                ResolvedMediaTrackConstraint::StringSequence(ResolvedValueSequenceConstraint {
                    exact: None,
                    ideal: Some(vec!["constraint".to_owned()]),
                });

            let settings = [MediaTrackSetting::String("setting".to_owned())];

            for setting in settings {
                let actual = constraint.fitness_distance(Some(&setting)).unwrap();

                let expected = 1.0;

                assert_eq!(actual, expected);
            }
        }

        #[test]
        fn incompatible_settings() {
            // As per step 3 of the `fitness distance` function from the W3C spec:
            // <https://www.w3.org/TR/mediacapture-streams/#dfn-fitness-distance>
            //
            // > If the constraint does not apply for this type of object, the fitness distance is 0
            // > (that is, the constraint does not influence the fitness distance).

            let constraint =
                ResolvedMediaTrackConstraint::StringSequence(ResolvedValueSequenceConstraint {
                    exact: None,
                    ideal: Some(vec!["constraint".to_owned()]),
                });

            let settings = [
                MediaTrackSetting::Bool(true),
                MediaTrackSetting::Integer(42),
                MediaTrackSetting::Float(4.2),
            ];

            for setting in settings {
                let actual = constraint.fitness_distance(Some(&setting)).unwrap();

                let expected = 0.0;

                assert_eq!(actual, expected);
            }
        }
    }
}