oximedia-core 0.1.3

Core types and traits for OxiMedia
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
//! Codec negotiation utilities for `OxiMedia`.
//!
//! This module provides types and functions for negotiating codec parameters
//! between local and remote endpoints, preferring hardware-accelerated codecs
//! when available.
//!
//! # Example
//!
//! ```
//! use oximedia_core::codec_negotiation::{CodecCapability, CodecNegotiator, negotiate};
//!
//! let local = vec![
//!     CodecCapability {
//!         name: "av1".to_string(),
//!         profiles: vec!["main".to_string()],
//!         max_level: 40,
//!         hardware_accelerated: false,
//!     },
//! ];
//! let remote = vec![
//!     CodecCapability {
//!         name: "av1".to_string(),
//!         profiles: vec!["main".to_string()],
//!         max_level: 30,
//!         hardware_accelerated: false,
//!     },
//! ];
//! let result = negotiate(&local, &remote);
//! assert!(result.is_some());
//! assert_eq!(result.expect("negotiation succeeded").selected_codec, "av1");
//! ```

#![allow(dead_code)]

/// Describes the codec capabilities of one endpoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodecCapability {
    /// Codec name (e.g. `"av1"`, `"vp9"`).
    pub name: String,
    /// List of supported codec profiles.
    pub profiles: Vec<String>,
    /// Maximum codec level supported (e.g. 40 for level 4.0).
    pub max_level: u32,
    /// Whether the codec benefits from hardware acceleration on this device.
    pub hardware_accelerated: bool,
}

impl CodecCapability {
    /// Creates a new `CodecCapability`.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        profiles: Vec<String>,
        max_level: u32,
        hardware_accelerated: bool,
    ) -> Self {
        Self {
            name: name.into(),
            profiles,
            max_level,
            hardware_accelerated,
        }
    }

    /// Returns `true` if `profile` is listed in this capability.
    #[must_use]
    pub fn supports_profile(&self, profile: &str) -> bool {
        self.profiles.iter().any(|p| p == profile)
    }

    /// Returns `true` if this codec uses hardware acceleration.
    #[must_use]
    pub fn is_hw_accelerated(&self) -> bool {
        self.hardware_accelerated
    }
}

/// Handles codec negotiation between a local and a remote set of capabilities.
#[derive(Debug, Default)]
pub struct CodecNegotiator {
    /// Codecs supported locally.
    pub local_caps: Vec<CodecCapability>,
    /// Codecs supported by the remote endpoint.
    pub remote_caps: Vec<CodecCapability>,
}

impl CodecNegotiator {
    /// Creates an empty `CodecNegotiator`.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a local codec capability.
    pub fn add_local(&mut self, cap: CodecCapability) {
        self.local_caps.push(cap);
    }

    /// Adds a remote codec capability.
    pub fn add_remote(&mut self, cap: CodecCapability) {
        self.remote_caps.push(cap);
    }

    /// Returns the names of codecs supported by both endpoints.
    #[must_use]
    pub fn common_codecs(&self) -> Vec<&str> {
        self.local_caps
            .iter()
            .filter(|l| self.remote_caps.iter().any(|r| r.name == l.name))
            .map(|l| l.name.as_str())
            .collect()
    }

    /// Returns the preferred common codec, favouring hardware-accelerated ones.
    ///
    /// Returns `None` when there are no codecs in common.
    #[must_use]
    pub fn preferred_codec(&self) -> Option<&str> {
        // Collect common names first.
        let common = self.common_codecs();
        if common.is_empty() {
            return None;
        }
        // Prefer hardware-accelerated; fall back to first common.
        for name in &common {
            if let Some(cap) = self.local_caps.iter().find(|c| &c.name.as_str() == name) {
                if cap.hardware_accelerated {
                    return Some(name);
                }
            }
        }
        common.into_iter().next()
    }
}

/// The result of a successful codec negotiation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NegotiationResult {
    /// The codec selected by both endpoints.
    pub selected_codec: String,
    /// The agreed-upon profile.
    pub profile: String,
    /// The agreed-upon level (minimum of local and remote max levels).
    pub level: u32,
    /// Whether the selected codec uses hardware acceleration on the local side.
    pub hardware_accelerated: bool,
}

impl NegotiationResult {
    /// Returns `true` if the selected codec uses hardware acceleration.
    #[must_use]
    pub fn is_hardware(&self) -> bool {
        self.hardware_accelerated
    }
}

/// Attempts to negotiate a codec between `local` and `remote` capability sets.
///
/// Hardware-accelerated codecs are preferred. The first common codec whose
/// profile list has at least one entry in common is selected.
///
/// Returns `None` when no mutually supported codec/profile pair exists.
#[must_use]
pub fn negotiate(
    local: &[CodecCapability],
    remote: &[CodecCapability],
) -> Option<NegotiationResult> {
    // Build a prioritised list: hw-accelerated local caps first.
    let mut ordered: Vec<&CodecCapability> = local.iter().collect();
    ordered.sort_by_key(|c| u8::from(!c.hardware_accelerated));

    for local_cap in ordered {
        if let Some(remote_cap) = remote.iter().find(|r| r.name == local_cap.name) {
            // Find a common profile.
            let common_profile = local_cap
                .profiles
                .iter()
                .find(|p| remote_cap.profiles.contains(p));
            if let Some(profile) = common_profile {
                let level = local_cap.max_level.min(remote_cap.max_level);
                return Some(NegotiationResult {
                    selected_codec: local_cap.name.clone(),
                    profile: profile.clone(),
                    level,
                    hardware_accelerated: local_cap.hardware_accelerated,
                });
            }
        }
    }
    None
}

// ─────────────────────────────────────────────────────────────────────────────
// Automatic format negotiation
// ─────────────────────────────────────────────────────────────────────────────

use crate::types::{PixelFormat, SampleFormat};

/// Pixel format capabilities of a codec.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PixelFormatCaps {
    /// Supported pixel formats, in order of preference.
    pub formats: Vec<PixelFormat>,
}

impl PixelFormatCaps {
    /// Creates new pixel-format capabilities.
    #[must_use]
    pub fn new(formats: Vec<PixelFormat>) -> Self {
        Self { formats }
    }

    /// Returns the first format supported by both sides, or `None`.
    #[must_use]
    pub fn negotiate(&self, other: &Self) -> Option<PixelFormat> {
        self.formats
            .iter()
            .find(|f| other.formats.contains(f))
            .copied()
    }

    /// Returns all formats supported by both sides.
    #[must_use]
    pub fn common_formats(&self, other: &Self) -> Vec<PixelFormat> {
        self.formats
            .iter()
            .filter(|f| other.formats.contains(f))
            .copied()
            .collect()
    }
}

/// Audio sample format capabilities of a codec.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SampleFormatCaps {
    /// Supported sample formats, in order of preference.
    pub formats: Vec<SampleFormat>,
}

impl SampleFormatCaps {
    /// Creates new sample-format capabilities.
    #[must_use]
    pub fn new(formats: Vec<SampleFormat>) -> Self {
        Self { formats }
    }

    /// Returns the first format supported by both sides, or `None`.
    #[must_use]
    pub fn negotiate(&self, other: &Self) -> Option<SampleFormat> {
        self.formats
            .iter()
            .find(|f| other.formats.contains(f))
            .copied()
    }

    /// Returns all formats supported by both sides.
    #[must_use]
    pub fn common_formats(&self, other: &Self) -> Vec<SampleFormat> {
        self.formats
            .iter()
            .filter(|f| other.formats.contains(f))
            .copied()
            .collect()
    }
}

/// Full format capabilities for automatic negotiation between encoder/decoder.
#[derive(Debug, Clone)]
pub struct FormatCapabilities {
    /// Codec name (e.g. "av1", "opus").
    pub codec_name: String,
    /// Supported pixel formats (empty for audio-only codecs).
    pub pixel_formats: PixelFormatCaps,
    /// Supported sample formats (empty for video-only codecs).
    pub sample_formats: SampleFormatCaps,
    /// Supported sample rates (empty for video-only codecs).
    pub sample_rates: Vec<u32>,
    /// Supported channel counts (empty for video-only codecs).
    pub channel_counts: Vec<u32>,
}

impl FormatCapabilities {
    /// Creates a new `FormatCapabilities` for a video codec.
    #[must_use]
    pub fn video(codec_name: impl Into<String>, pixel_formats: Vec<PixelFormat>) -> Self {
        Self {
            codec_name: codec_name.into(),
            pixel_formats: PixelFormatCaps::new(pixel_formats),
            sample_formats: SampleFormatCaps::new(vec![]),
            sample_rates: vec![],
            channel_counts: vec![],
        }
    }

    /// Creates a new `FormatCapabilities` for an audio codec.
    #[must_use]
    pub fn audio(
        codec_name: impl Into<String>,
        sample_formats: Vec<SampleFormat>,
        sample_rates: Vec<u32>,
        channel_counts: Vec<u32>,
    ) -> Self {
        Self {
            codec_name: codec_name.into(),
            pixel_formats: PixelFormatCaps::new(vec![]),
            sample_formats: SampleFormatCaps::new(sample_formats),
            sample_rates,
            channel_counts,
        }
    }
}

/// Result of automatic format negotiation between encoder and decoder.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatNegotiationResult {
    /// Negotiated pixel format (if video).
    pub pixel_format: Option<PixelFormat>,
    /// Negotiated sample format (if audio).
    pub sample_format: Option<SampleFormat>,
    /// Negotiated sample rate (if audio).
    pub sample_rate: Option<u32>,
    /// Negotiated channel count (if audio).
    pub channel_count: Option<u32>,
}

/// Negotiates the best format parameters between a decoder's output capabilities
/// and an encoder's input capabilities.
///
/// For each parameter, the first mutually-supported value (in the decoder's
/// preference order) is chosen. Returns `None` if the two capability sets have
/// no format in common for the relevant media type.
#[must_use]
pub fn negotiate_formats(
    decoder: &FormatCapabilities,
    encoder: &FormatCapabilities,
) -> Option<FormatNegotiationResult> {
    let is_video =
        !decoder.pixel_formats.formats.is_empty() && !encoder.pixel_formats.formats.is_empty();
    let is_audio =
        !decoder.sample_formats.formats.is_empty() && !encoder.sample_formats.formats.is_empty();

    if !is_video && !is_audio {
        return None;
    }

    let pixel_format = if is_video {
        let pf = decoder.pixel_formats.negotiate(&encoder.pixel_formats);
        pf?;
        pf
    } else {
        None
    };

    let sample_format = if is_audio {
        let sf = decoder.sample_formats.negotiate(&encoder.sample_formats);
        sf?;
        sf
    } else {
        None
    };

    let sample_rate = if is_audio {
        decoder
            .sample_rates
            .iter()
            .find(|r| encoder.sample_rates.contains(r))
            .copied()
    } else {
        None
    };

    let channel_count = if is_audio {
        decoder
            .channel_counts
            .iter()
            .find(|c| encoder.channel_counts.contains(c))
            .copied()
    } else {
        None
    };

    Some(FormatNegotiationResult {
        pixel_format,
        sample_format,
        sample_rate,
        channel_count,
    })
}

// ─────────────────────────────────────────────────────────────────────────────
// Resolution / bitrate constraints for full auto-negotiation
// ─────────────────────────────────────────────────────────────────────────────

/// Resolution constraint for video negotiation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolutionRange {
    /// Minimum supported width.
    pub min_width: u32,
    /// Maximum supported width.
    pub max_width: u32,
    /// Minimum supported height.
    pub min_height: u32,
    /// Maximum supported height.
    pub max_height: u32,
}

impl ResolutionRange {
    /// Creates a new resolution range.
    #[must_use]
    pub fn new(min_width: u32, max_width: u32, min_height: u32, max_height: u32) -> Self {
        Self {
            min_width,
            max_width,
            min_height,
            max_height,
        }
    }

    /// Returns whether the given dimensions fit within this range.
    #[must_use]
    pub fn contains(&self, width: u32, height: u32) -> bool {
        width >= self.min_width
            && width <= self.max_width
            && height >= self.min_height
            && height <= self.max_height
    }

    /// Returns the intersection of two resolution ranges, or `None` if they don't overlap.
    #[must_use]
    pub fn intersect(&self, other: &Self) -> Option<Self> {
        let min_w = self.min_width.max(other.min_width);
        let max_w = self.max_width.min(other.max_width);
        let min_h = self.min_height.max(other.min_height);
        let max_h = self.max_height.min(other.max_height);
        if min_w <= max_w && min_h <= max_h {
            Some(Self::new(min_w, max_w, min_h, max_h))
        } else {
            None
        }
    }
}

impl Default for ResolutionRange {
    fn default() -> Self {
        Self {
            min_width: 1,
            max_width: 8192,
            min_height: 1,
            max_height: 4320,
        }
    }
}

/// Bitrate constraint for negotiation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BitrateRange {
    /// Minimum bitrate in bits per second.
    pub min_bps: u64,
    /// Maximum bitrate in bits per second.
    pub max_bps: u64,
}

impl BitrateRange {
    /// Creates a new bitrate range.
    #[must_use]
    pub fn new(min_bps: u64, max_bps: u64) -> Self {
        Self { min_bps, max_bps }
    }

    /// Returns whether the given bitrate fits within this range.
    #[must_use]
    pub fn contains(&self, bps: u64) -> bool {
        bps >= self.min_bps && bps <= self.max_bps
    }

    /// Returns the intersection of two bitrate ranges, or `None` if they don't overlap.
    #[must_use]
    pub fn intersect(&self, other: &Self) -> Option<Self> {
        let min = self.min_bps.max(other.min_bps);
        let max = self.max_bps.min(other.max_bps);
        if min <= max {
            Some(Self::new(min, max))
        } else {
            None
        }
    }
}

impl Default for BitrateRange {
    fn default() -> Self {
        Self {
            min_bps: 0,
            max_bps: u64::MAX,
        }
    }
}

/// Full endpoint capabilities for automatic encoder/decoder negotiation.
///
/// Combines codec capabilities, format capabilities, and hardware constraints
/// into a single description that `AutoNegotiator` can reason about.
#[derive(Debug, Clone)]
pub struct EndpointCapabilities {
    /// Codec-level capabilities (profiles, levels, hw).
    pub codec: CodecCapability,
    /// Format capabilities (pixel formats, sample formats, sample rates, channels).
    pub formats: FormatCapabilities,
    /// Resolution constraint (video only; ignored for audio).
    pub resolution: ResolutionRange,
    /// Bitrate constraint.
    pub bitrate: BitrateRange,
}

impl EndpointCapabilities {
    /// Creates video endpoint capabilities.
    #[must_use]
    pub fn video(
        codec: CodecCapability,
        pixel_formats: Vec<PixelFormat>,
        resolution: ResolutionRange,
        bitrate: BitrateRange,
    ) -> Self {
        Self {
            formats: FormatCapabilities::video(&codec.name, pixel_formats),
            codec,
            resolution,
            bitrate,
        }
    }

    /// Creates audio endpoint capabilities.
    #[must_use]
    pub fn audio(
        codec: CodecCapability,
        sample_formats: Vec<SampleFormat>,
        sample_rates: Vec<u32>,
        channel_counts: Vec<u32>,
        bitrate: BitrateRange,
    ) -> Self {
        Self {
            formats: FormatCapabilities::audio(
                &codec.name,
                sample_formats,
                sample_rates,
                channel_counts,
            ),
            codec,
            resolution: ResolutionRange::default(),
            bitrate,
        }
    }
}

/// Result of full automatic negotiation.
#[derive(Debug, Clone, PartialEq)]
pub struct AutoNegotiationResult {
    /// Selected codec name.
    pub codec: String,
    /// Agreed profile.
    pub profile: String,
    /// Agreed level (min of both sides).
    pub level: u32,
    /// Whether hardware acceleration is available.
    pub hardware_accelerated: bool,
    /// Negotiated format parameters.
    pub format: FormatNegotiationResult,
    /// Negotiated resolution range (video only).
    pub resolution: Option<ResolutionRange>,
    /// Negotiated bitrate range.
    pub bitrate: Option<BitrateRange>,
    /// Quality score (0.0 - 1.0, higher is better).
    pub score: f64,
}

/// Automatic negotiator that finds the best encoder/decoder pairing.
///
/// Combines codec negotiation, format negotiation, resolution/bitrate constraint
/// intersection, and quality scoring into a single pass.
///
/// # Example
///
/// ```
/// use oximedia_core::codec_negotiation::*;
/// use oximedia_core::types::{PixelFormat, SampleFormat};
///
/// let decoder = EndpointCapabilities::video(
///     CodecCapability::new("av1", vec!["main".into()], 50, true),
///     vec![PixelFormat::Yuv420p, PixelFormat::Yuv420p10le],
///     ResolutionRange::new(1, 3840, 1, 2160),
///     BitrateRange::new(500_000, 20_000_000),
/// );
/// let encoder = EndpointCapabilities::video(
///     CodecCapability::new("av1", vec!["main".into()], 40, false),
///     vec![PixelFormat::Yuv420p10le, PixelFormat::Yuv420p],
///     ResolutionRange::new(1, 1920, 1, 1080),
///     BitrateRange::new(1_000_000, 15_000_000),
/// );
/// let result = auto_negotiate(&decoder, &encoder).expect("should negotiate");
/// assert_eq!(result.codec, "av1");
/// assert_eq!(result.format.pixel_format, Some(PixelFormat::Yuv420p));
/// assert!(result.resolution.is_some());
/// ```
#[must_use]
pub fn auto_negotiate(
    decoder: &EndpointCapabilities,
    encoder: &EndpointCapabilities,
) -> Option<AutoNegotiationResult> {
    // 1. Codec-level negotiation
    let codec_result = negotiate(
        std::slice::from_ref(&decoder.codec),
        std::slice::from_ref(&encoder.codec),
    )?;

    // 2. Format negotiation
    let format_result = negotiate_formats(&decoder.formats, &encoder.formats)?;

    // 3. Resolution intersection
    let resolution = decoder.resolution.intersect(&encoder.resolution);

    // 4. Bitrate intersection
    let bitrate = decoder.bitrate.intersect(&encoder.bitrate);

    // 5. Compute quality score
    let score = compute_score(&codec_result, &format_result, &resolution, &bitrate);

    Some(AutoNegotiationResult {
        codec: codec_result.selected_codec,
        profile: codec_result.profile,
        level: codec_result.level,
        hardware_accelerated: codec_result.hardware_accelerated,
        format: format_result,
        resolution,
        bitrate,
        score,
    })
}

/// Computes a quality score in [0.0, 1.0] for a negotiation result.
///
/// Factors:
/// - Hardware acceleration: +0.2
/// - Higher codec level: up to +0.3
/// - Higher bit-depth pixel format: up to +0.2
/// - Resolution available: +0.15
/// - Bitrate available: +0.15
fn compute_score(
    codec: &NegotiationResult,
    format: &FormatNegotiationResult,
    resolution: &Option<ResolutionRange>,
    bitrate: &Option<BitrateRange>,
) -> f64 {
    let mut score = 0.0;

    // Hardware acceleration bonus
    if codec.hardware_accelerated {
        score += 0.2;
    }

    // Codec level score (normalised to 0..0.3 assuming level range 10..63)
    let level_norm = f64::from(codec.level.min(63).saturating_sub(10)) / 53.0;
    score += level_norm * 0.3;

    // Pixel format bit depth score
    if let Some(pf) = format.pixel_format {
        let depth_score = f64::from(pf.bits_per_component().min(16)) / 16.0;
        score += depth_score * 0.2;
    }

    // Resolution available
    if resolution.is_some() {
        score += 0.15;
    }

    // Bitrate available
    if bitrate.is_some() {
        score += 0.15;
    }

    // Clamp to [0.0, 1.0]
    score.min(1.0)
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    fn av1_cap(hw: bool) -> CodecCapability {
        CodecCapability::new("av1", vec!["main".to_string(), "high".to_string()], 40, hw)
    }

    fn vp9_cap() -> CodecCapability {
        CodecCapability::new("vp9", vec!["profile0".to_string()], 50, false)
    }

    // 1. supports_profile – positive
    #[test]
    fn test_supports_profile_positive() {
        let cap = av1_cap(false);
        assert!(cap.supports_profile("main"));
        assert!(cap.supports_profile("high"));
    }

    // 2. supports_profile – negative
    #[test]
    fn test_supports_profile_negative() {
        let cap = av1_cap(false);
        assert!(!cap.supports_profile("baseline"));
    }

    // 3. is_hw_accelerated
    #[test]
    fn test_is_hw_accelerated() {
        assert!(av1_cap(true).is_hw_accelerated());
        assert!(!av1_cap(false).is_hw_accelerated());
    }

    // 4. CodecNegotiator::common_codecs – overlap
    #[test]
    fn test_common_codecs_overlap() {
        let mut neg = CodecNegotiator::new();
        neg.add_local(av1_cap(false));
        neg.add_local(vp9_cap());
        neg.add_remote(av1_cap(false));
        let common = neg.common_codecs();
        assert_eq!(common, vec!["av1"]);
    }

    // 5. CodecNegotiator::common_codecs – no overlap
    #[test]
    fn test_common_codecs_no_overlap() {
        let mut neg = CodecNegotiator::new();
        neg.add_local(vp9_cap());
        neg.add_remote(av1_cap(false));
        assert!(neg.common_codecs().is_empty());
    }

    // 6. preferred_codec – hw preferred
    #[test]
    fn test_preferred_codec_hw_first() {
        let mut neg = CodecNegotiator::new();
        neg.add_local(vp9_cap()); // software
        neg.add_local(av1_cap(true)); // hardware
        neg.add_remote(vp9_cap());
        neg.add_remote(av1_cap(true));
        // av1 is hw, should be preferred
        assert_eq!(neg.preferred_codec(), Some("av1"));
    }

    // 7. preferred_codec – no common
    #[test]
    fn test_preferred_codec_none() {
        let mut neg = CodecNegotiator::new();
        neg.add_local(vp9_cap());
        neg.add_remote(av1_cap(false));
        assert!(neg.preferred_codec().is_none());
    }

    // 8. preferred_codec – falls back to first when no hw
    #[test]
    fn test_preferred_codec_fallback() {
        let mut neg = CodecNegotiator::new();
        neg.add_local(av1_cap(false));
        neg.add_local(vp9_cap());
        neg.add_remote(av1_cap(false));
        neg.add_remote(vp9_cap());
        // No hw acceleration; first common codec returned
        let pref = neg.preferred_codec();
        assert!(pref.is_some());
    }

    // 9. negotiate – success
    #[test]
    fn test_negotiate_success() {
        let local = vec![av1_cap(false)];
        let remote = vec![av1_cap(false)];
        let result = negotiate(&local, &remote).expect("negotiation should succeed");
        assert_eq!(result.selected_codec, "av1");
        assert!(result.profile == "main" || result.profile == "high");
        assert_eq!(result.level, 40);
        assert!(!result.is_hardware());
    }

    // 10. negotiate – hw preferred
    #[test]
    fn test_negotiate_prefers_hw() {
        let local = vec![vp9_cap(), av1_cap(true)];
        let remote = vec![vp9_cap(), av1_cap(true)];
        let result = negotiate(&local, &remote).expect("negotiation should succeed");
        assert_eq!(result.selected_codec, "av1");
        assert!(result.is_hardware());
    }

    // 11. negotiate – level is min of both
    #[test]
    fn test_negotiate_level_min() {
        let local = vec![CodecCapability::new(
            "av1",
            vec!["main".to_string()],
            50,
            false,
        )];
        let remote = vec![CodecCapability::new(
            "av1",
            vec!["main".to_string()],
            30,
            false,
        )];
        let result = negotiate(&local, &remote).expect("negotiation should succeed");
        assert_eq!(result.level, 30);
    }

    // 12. negotiate – no common codec returns None
    #[test]
    fn test_negotiate_no_common() {
        let local = vec![av1_cap(false)];
        let remote = vec![vp9_cap()];
        assert!(negotiate(&local, &remote).is_none());
    }

    // 13. negotiate – profile mismatch returns None
    #[test]
    fn test_negotiate_profile_mismatch() {
        let local = vec![CodecCapability::new(
            "av1",
            vec!["high".to_string()],
            40,
            false,
        )];
        let remote = vec![CodecCapability::new(
            "av1",
            vec!["baseline".to_string()],
            40,
            false,
        )];
        assert!(negotiate(&local, &remote).is_none());
    }

    // 14. NegotiationResult::is_hardware
    #[test]
    fn test_negotiation_result_is_hardware() {
        let r = NegotiationResult {
            selected_codec: "av1".to_string(),
            profile: "main".to_string(),
            level: 40,
            hardware_accelerated: true,
        };
        assert!(r.is_hardware());
        let r2 = NegotiationResult {
            hardware_accelerated: false,
            ..r
        };
        assert!(!r2.is_hardware());
    }

    // ── Format negotiation tests ──────────────────────────────────────

    #[test]
    fn test_pixel_format_negotiate_common() {
        let dec = PixelFormatCaps::new(vec![PixelFormat::Yuv420p, PixelFormat::Nv12]);
        let enc = PixelFormatCaps::new(vec![PixelFormat::Nv12, PixelFormat::Yuv420p]);
        // Decoder prefers Yuv420p, encoder also supports it
        assert_eq!(dec.negotiate(&enc), Some(PixelFormat::Yuv420p));
    }

    #[test]
    fn test_pixel_format_negotiate_no_common() {
        let dec = PixelFormatCaps::new(vec![PixelFormat::Yuv420p]);
        let enc = PixelFormatCaps::new(vec![PixelFormat::Rgb24]);
        assert_eq!(dec.negotiate(&enc), None);
    }

    #[test]
    fn test_pixel_format_common_formats() {
        let dec = PixelFormatCaps::new(vec![
            PixelFormat::Yuv420p,
            PixelFormat::Nv12,
            PixelFormat::Rgb24,
        ]);
        let enc = PixelFormatCaps::new(vec![PixelFormat::Nv12, PixelFormat::Rgb24]);
        let common = dec.common_formats(&enc);
        assert_eq!(common, vec![PixelFormat::Nv12, PixelFormat::Rgb24]);
    }

    #[test]
    fn test_sample_format_negotiate_common() {
        let dec = SampleFormatCaps::new(vec![SampleFormat::F32, SampleFormat::S16]);
        let enc = SampleFormatCaps::new(vec![SampleFormat::S16, SampleFormat::S24]);
        assert_eq!(dec.negotiate(&enc), Some(SampleFormat::S16));
    }

    #[test]
    fn test_sample_format_negotiate_no_common() {
        let dec = SampleFormatCaps::new(vec![SampleFormat::F32]);
        let enc = SampleFormatCaps::new(vec![SampleFormat::S24]);
        assert_eq!(dec.negotiate(&enc), None);
    }

    #[test]
    fn test_sample_format_common_formats() {
        let dec = SampleFormatCaps::new(vec![
            SampleFormat::F32,
            SampleFormat::S16,
            SampleFormat::S24,
        ]);
        let enc = SampleFormatCaps::new(vec![SampleFormat::S24, SampleFormat::F32]);
        let common = dec.common_formats(&enc);
        assert_eq!(common, vec![SampleFormat::F32, SampleFormat::S24]);
    }

    #[test]
    fn test_negotiate_formats_video() {
        let decoder =
            FormatCapabilities::video("av1", vec![PixelFormat::Yuv420p, PixelFormat::Yuv420p10le]);
        let encoder =
            FormatCapabilities::video("av1", vec![PixelFormat::Yuv420p10le, PixelFormat::Yuv420p]);
        let result = negotiate_formats(&decoder, &encoder).expect("should negotiate");
        assert_eq!(result.pixel_format, Some(PixelFormat::Yuv420p));
        assert_eq!(result.sample_format, None);
    }

    #[test]
    fn test_negotiate_formats_audio() {
        let decoder = FormatCapabilities::audio(
            "opus",
            vec![SampleFormat::F32, SampleFormat::S16],
            vec![48000, 44100],
            vec![2, 1],
        );
        let encoder = FormatCapabilities::audio(
            "opus",
            vec![SampleFormat::S16, SampleFormat::F32],
            vec![48000],
            vec![2],
        );
        let result = negotiate_formats(&decoder, &encoder).expect("should negotiate");
        assert_eq!(result.sample_format, Some(SampleFormat::F32));
        assert_eq!(result.sample_rate, Some(48000));
        assert_eq!(result.channel_count, Some(2));
        assert_eq!(result.pixel_format, None);
    }

    #[test]
    fn test_negotiate_formats_no_common_pixel_format() {
        let decoder = FormatCapabilities::video("av1", vec![PixelFormat::Yuv420p]);
        let encoder = FormatCapabilities::video("av1", vec![PixelFormat::Rgb24]);
        assert!(negotiate_formats(&decoder, &encoder).is_none());
    }

    #[test]
    fn test_negotiate_formats_no_common_sample_format() {
        let decoder =
            FormatCapabilities::audio("opus", vec![SampleFormat::F32], vec![48000], vec![2]);
        let encoder =
            FormatCapabilities::audio("opus", vec![SampleFormat::S24], vec![48000], vec![2]);
        assert!(negotiate_formats(&decoder, &encoder).is_none());
    }

    #[test]
    fn test_negotiate_formats_empty_caps() {
        let decoder = FormatCapabilities::video("av1", vec![]);
        let encoder = FormatCapabilities::video("av1", vec![]);
        assert!(negotiate_formats(&decoder, &encoder).is_none());
    }

    #[test]
    fn test_negotiate_formats_video_with_semi_planar() {
        let decoder = FormatCapabilities::video("av1", vec![PixelFormat::Nv12, PixelFormat::P010]);
        let encoder =
            FormatCapabilities::video("av1", vec![PixelFormat::P010, PixelFormat::Yuv420p]);
        let result = negotiate_formats(&decoder, &encoder).expect("should negotiate");
        assert_eq!(result.pixel_format, Some(PixelFormat::P010));
    }

    #[test]
    fn test_format_capabilities_video_constructor() {
        let caps = FormatCapabilities::video("vp9", vec![PixelFormat::Yuv420p]);
        assert_eq!(caps.codec_name, "vp9");
        assert_eq!(caps.pixel_formats.formats.len(), 1);
        assert!(caps.sample_formats.formats.is_empty());
        assert!(caps.sample_rates.is_empty());
        assert!(caps.channel_counts.is_empty());
    }

    #[test]
    fn test_format_capabilities_audio_constructor() {
        let caps = FormatCapabilities::audio(
            "flac",
            vec![SampleFormat::S16, SampleFormat::S24],
            vec![44100, 48000, 96000],
            vec![1, 2],
        );
        assert_eq!(caps.codec_name, "flac");
        assert!(caps.pixel_formats.formats.is_empty());
        assert_eq!(caps.sample_formats.formats.len(), 2);
        assert_eq!(caps.sample_rates.len(), 3);
        assert_eq!(caps.channel_counts.len(), 2);
    }

    // ── ResolutionRange tests ───────────────────────────────────────

    #[test]
    fn test_resolution_range_contains() {
        let r = ResolutionRange::new(1, 1920, 1, 1080);
        assert!(r.contains(1920, 1080));
        assert!(r.contains(1, 1));
        assert!(r.contains(1280, 720));
        assert!(!r.contains(3840, 2160));
        assert!(!r.contains(0, 0));
    }

    #[test]
    fn test_resolution_range_intersect() {
        let a = ResolutionRange::new(1, 3840, 1, 2160);
        let b = ResolutionRange::new(640, 1920, 480, 1080);
        let intersect = a.intersect(&b).expect("should intersect");
        assert_eq!(intersect.min_width, 640);
        assert_eq!(intersect.max_width, 1920);
        assert_eq!(intersect.min_height, 480);
        assert_eq!(intersect.max_height, 1080);
    }

    #[test]
    fn test_resolution_range_no_intersect() {
        let a = ResolutionRange::new(1, 640, 1, 480);
        let b = ResolutionRange::new(1920, 3840, 1080, 2160);
        assert!(a.intersect(&b).is_none());
    }

    #[test]
    fn test_resolution_range_default() {
        let r = ResolutionRange::default();
        assert!(r.contains(1920, 1080));
        assert!(r.contains(7680, 4320));
    }

    // ── BitrateRange tests ──────────────────────────────────────────

    #[test]
    fn test_bitrate_range_contains() {
        let b = BitrateRange::new(1_000_000, 10_000_000);
        assert!(b.contains(5_000_000));
        assert!(b.contains(1_000_000));
        assert!(b.contains(10_000_000));
        assert!(!b.contains(500_000));
        assert!(!b.contains(20_000_000));
    }

    #[test]
    fn test_bitrate_range_intersect() {
        let a = BitrateRange::new(500_000, 20_000_000);
        let b = BitrateRange::new(1_000_000, 15_000_000);
        let intersect = a.intersect(&b).expect("should intersect");
        assert_eq!(intersect.min_bps, 1_000_000);
        assert_eq!(intersect.max_bps, 15_000_000);
    }

    #[test]
    fn test_bitrate_range_no_intersect() {
        let a = BitrateRange::new(1_000_000, 2_000_000);
        let b = BitrateRange::new(5_000_000, 10_000_000);
        assert!(a.intersect(&b).is_none());
    }

    #[test]
    fn test_bitrate_range_default() {
        let b = BitrateRange::default();
        assert!(b.contains(0));
        assert!(b.contains(1_000_000_000));
    }

    // ── auto_negotiate tests ────────────────────────────────────────

    #[test]
    fn test_auto_negotiate_video_success() {
        let decoder = EndpointCapabilities::video(
            CodecCapability::new("av1", vec!["main".into()], 50, true),
            vec![PixelFormat::Yuv420p, PixelFormat::Yuv420p10le],
            ResolutionRange::new(1, 3840, 1, 2160),
            BitrateRange::new(500_000, 20_000_000),
        );
        let encoder = EndpointCapabilities::video(
            CodecCapability::new("av1", vec!["main".into()], 40, false),
            vec![PixelFormat::Yuv420p10le, PixelFormat::Yuv420p],
            ResolutionRange::new(1, 1920, 1, 1080),
            BitrateRange::new(1_000_000, 15_000_000),
        );
        let result = auto_negotiate(&decoder, &encoder).expect("should negotiate");
        assert_eq!(result.codec, "av1");
        assert_eq!(result.profile, "main");
        assert_eq!(result.level, 40); // min of 50 and 40
        assert!(result.hardware_accelerated); // decoder has hw
        assert_eq!(result.format.pixel_format, Some(PixelFormat::Yuv420p));

        let res = result.resolution.expect("should have resolution");
        assert_eq!(res.max_width, 1920);
        assert_eq!(res.max_height, 1080);

        let br = result.bitrate.expect("should have bitrate");
        assert_eq!(br.min_bps, 1_000_000);
        assert_eq!(br.max_bps, 15_000_000);

        assert!(result.score > 0.0);
        assert!(result.score <= 1.0);
    }

    #[test]
    fn test_auto_negotiate_audio_success() {
        let decoder = EndpointCapabilities::audio(
            CodecCapability::new("opus", vec!["default".into()], 0, false),
            vec![SampleFormat::F32, SampleFormat::S16],
            vec![48000, 44100],
            vec![2, 1],
            BitrateRange::new(64_000, 510_000),
        );
        let encoder = EndpointCapabilities::audio(
            CodecCapability::new("opus", vec!["default".into()], 0, false),
            vec![SampleFormat::S16, SampleFormat::F32],
            vec![48000],
            vec![2],
            BitrateRange::new(96_000, 256_000),
        );
        let result = auto_negotiate(&decoder, &encoder).expect("should negotiate");
        assert_eq!(result.codec, "opus");
        assert_eq!(result.format.sample_format, Some(SampleFormat::F32));
        assert_eq!(result.format.sample_rate, Some(48000));
        assert_eq!(result.format.channel_count, Some(2));

        let br = result.bitrate.expect("should have bitrate");
        assert_eq!(br.min_bps, 96_000);
        assert_eq!(br.max_bps, 256_000);
    }

    #[test]
    fn test_auto_negotiate_codec_mismatch() {
        let decoder = EndpointCapabilities::video(
            CodecCapability::new("av1", vec!["main".into()], 40, false),
            vec![PixelFormat::Yuv420p],
            ResolutionRange::default(),
            BitrateRange::default(),
        );
        let encoder = EndpointCapabilities::video(
            CodecCapability::new("vp9", vec!["profile0".into()], 40, false),
            vec![PixelFormat::Yuv420p],
            ResolutionRange::default(),
            BitrateRange::default(),
        );
        assert!(auto_negotiate(&decoder, &encoder).is_none());
    }

    #[test]
    fn test_auto_negotiate_format_mismatch() {
        let decoder = EndpointCapabilities::video(
            CodecCapability::new("av1", vec!["main".into()], 40, false),
            vec![PixelFormat::Yuv420p],
            ResolutionRange::default(),
            BitrateRange::default(),
        );
        let encoder = EndpointCapabilities::video(
            CodecCapability::new("av1", vec!["main".into()], 40, false),
            vec![PixelFormat::Rgb24],
            ResolutionRange::default(),
            BitrateRange::default(),
        );
        assert!(auto_negotiate(&decoder, &encoder).is_none());
    }

    #[test]
    fn test_auto_negotiate_hw_boosts_score() {
        let make_endpoint = |hw: bool| {
            EndpointCapabilities::video(
                CodecCapability::new("av1", vec!["main".into()], 40, hw),
                vec![PixelFormat::Yuv420p],
                ResolutionRange::default(),
                BitrateRange::default(),
            )
        };
        let hw_result =
            auto_negotiate(&make_endpoint(true), &make_endpoint(true)).expect("should negotiate");
        let sw_result =
            auto_negotiate(&make_endpoint(false), &make_endpoint(false)).expect("should negotiate");
        assert!(hw_result.score > sw_result.score);
    }

    #[test]
    fn test_auto_negotiate_resolution_no_overlap_still_returns() {
        // Resolution ranges don't overlap, but codec+format do => result returned with None resolution
        let decoder = EndpointCapabilities::video(
            CodecCapability::new("av1", vec!["main".into()], 40, false),
            vec![PixelFormat::Yuv420p],
            ResolutionRange::new(1, 640, 1, 480),
            BitrateRange::default(),
        );
        let encoder = EndpointCapabilities::video(
            CodecCapability::new("av1", vec!["main".into()], 40, false),
            vec![PixelFormat::Yuv420p],
            ResolutionRange::new(1920, 3840, 1080, 2160),
            BitrateRange::default(),
        );
        let result = auto_negotiate(&decoder, &encoder).expect("should still negotiate");
        assert!(result.resolution.is_none());
    }

    #[test]
    fn test_score_range() {
        // Score should always be in [0, 1]
        let endpoint = EndpointCapabilities::video(
            CodecCapability::new("av1", vec!["main".into()], 63, true),
            vec![PixelFormat::Yuv420p10le],
            ResolutionRange::default(),
            BitrateRange::default(),
        );
        let result = auto_negotiate(&endpoint, &endpoint).expect("should negotiate");
        assert!(result.score >= 0.0);
        assert!(result.score <= 1.0);
    }

    #[test]
    fn test_endpoint_capabilities_video_constructor() {
        let ep = EndpointCapabilities::video(
            CodecCapability::new("vp9", vec!["profile0".into()], 50, false),
            vec![PixelFormat::Yuv420p, PixelFormat::Nv12],
            ResolutionRange::new(1, 1920, 1, 1080),
            BitrateRange::new(1_000_000, 10_000_000),
        );
        assert_eq!(ep.codec.name, "vp9");
        assert_eq!(ep.formats.pixel_formats.formats.len(), 2);
        assert_eq!(ep.resolution.max_width, 1920);
        assert_eq!(ep.bitrate.max_bps, 10_000_000);
    }

    #[test]
    fn test_endpoint_capabilities_audio_constructor() {
        let ep = EndpointCapabilities::audio(
            CodecCapability::new("flac", vec!["default".into()], 0, false),
            vec![SampleFormat::S16, SampleFormat::S24],
            vec![44100, 48000, 96000],
            vec![1, 2],
            BitrateRange::new(0, 5_000_000),
        );
        assert_eq!(ep.codec.name, "flac");
        assert_eq!(ep.formats.sample_formats.formats.len(), 2);
        assert_eq!(ep.formats.sample_rates.len(), 3);
    }
}