1use std::sync::Mutex;
22
23use serde::{Deserialize, Serialize};
24
25use super::types::VideoCodec;
26
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
32#[serde(rename_all = "snake_case")]
33#[non_exhaustive]
34pub enum VideoCodecPreference {
35 #[default]
39 Automatic,
40 PreferH264,
43 PreferVp8,
46}
47
48impl VideoCodecPreference {
49 pub fn as_str(self) -> &'static str {
51 match self {
52 VideoCodecPreference::Automatic => "automatic",
53 VideoCodecPreference::PreferH264 => "prefer_h264",
54 VideoCodecPreference::PreferVp8 => "prefer_vp8",
55 }
56 }
57
58 pub fn from_name(name: &str) -> Option<VideoCodecPreference> {
60 match name {
61 "automatic" => Some(VideoCodecPreference::Automatic),
62 "prefer_h264" => Some(VideoCodecPreference::PreferH264),
63 "prefer_vp8" => Some(VideoCodecPreference::PreferVp8),
64 _ => None,
65 }
66 }
67}
68
69#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78#[non_exhaustive]
79pub enum H264Detection {
80 Usable,
82 NotDetected,
85 Unconfirmed,
88 NoPlatformCheck,
91}
92
93impl H264Detection {
94 pub fn is_usable(self) -> bool {
96 self == H264Detection::Usable
97 }
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
104#[serde(rename_all = "snake_case")]
105#[non_exhaustive]
106pub enum CodecPreferenceReason {
107 NotDetected,
110 Platform,
114 Policy,
117}
118
119impl CodecPreferenceReason {
120 pub fn as_str(self) -> &'static str {
122 match self {
123 CodecPreferenceReason::NotDetected => "not_detected",
124 CodecPreferenceReason::Platform => "platform",
125 CodecPreferenceReason::Policy => "policy",
126 }
127 }
128}
129
130pub fn effective_publish_codec(
146 pref: VideoCodecPreference,
147 detected: H264Detection,
148) -> (VideoCodec, Option<CodecPreferenceReason>) {
149 match (pref, detected) {
150 (VideoCodecPreference::PreferVp8, _) => (VideoCodec::Vp8, None),
151 (_, H264Detection::Usable) => (VideoCodec::H264, None),
152 (VideoCodecPreference::PreferH264, H264Detection::NotDetected) => {
153 (VideoCodec::Vp8, Some(CodecPreferenceReason::NotDetected))
154 }
155 (VideoCodecPreference::PreferH264, _) => {
156 (VideoCodec::Vp8, Some(CodecPreferenceReason::Platform))
157 }
158 _ => (VideoCodec::Vp8, None),
159 }
160}
161
162pub fn effective_publish_codec_under_policy(
167 pref: VideoCodecPreference,
168 detected: H264Detection,
169 h264_allowed: bool,
170) -> (VideoCodec, Option<CodecPreferenceReason>) {
171 match effective_publish_codec(pref, detected) {
172 (VideoCodec::H264, _) if !h264_allowed => {
173 let reason =
174 (pref == VideoCodecPreference::PreferH264).then_some(CodecPreferenceReason::Policy);
175 (VideoCodec::Vp8, reason)
176 }
177 out => out,
178 }
179}
180
181#[cfg(feature = "video-core")]
185const NO_H264_BACKENDS: [&str; 4] = ["linux", "android", "windows", "null"];
186
187#[cfg(feature = "video-core")]
195pub fn h264_encode_detection(caps: &kessel_video::Capabilities) -> H264Detection {
196 use kessel_video::{CodecDirection, Implementation};
197 if NO_H264_BACKENDS.contains(&caps.backend) {
198 return H264Detection::NoPlatformCheck;
199 }
200 let hardware = caps.codecs.iter().any(|c| {
201 c.codec == kessel_video::VideoCodec::H264
202 && c.direction == CodecDirection::Encode
203 && c.implementation == Implementation::Hardware
204 });
205 if hardware {
206 H264Detection::Usable
207 } else if ios_before_17_4(&caps.os) {
208 H264Detection::Unconfirmed
209 } else {
210 H264Detection::NotDetected
211 }
212}
213
214#[cfg(feature = "video-core")]
215impl H264Detection {
216 pub fn from_session(implementation: kessel_video::Implementation) -> H264Detection {
220 match implementation {
221 kessel_video::Implementation::Hardware => H264Detection::Usable,
222 kessel_video::Implementation::Software => H264Detection::NotDetected,
223 _ => H264Detection::Unconfirmed,
224 }
225 }
226}
227
228#[cfg(feature = "video-core")]
231fn ios_before_17_4(os: &str) -> bool {
232 let Some(rest) = os.strip_prefix("iOS") else {
233 return false;
234 };
235 let Some(version) = rest
236 .split(|c: char| !(c.is_ascii_digit() || c == '.'))
237 .find(|t| t.contains(|c: char| c.is_ascii_digit()))
238 else {
239 return false;
240 };
241 let mut parts = version.split('.').map(|p| p.parse::<u32>().ok());
242 match (parts.next().flatten(), parts.next().flatten().unwrap_or(0)) {
243 (Some(major), minor) => (major, minor) < (17, 4),
244 _ => false,
245 }
246}
247
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
250pub(crate) struct CodecSet {
251 h264: bool,
252}
253
254impl CodecSet {
255 #[cfg_attr(not(test), allow(dead_code))]
257 pub(crate) const VP8_ONLY: CodecSet = CodecSet { h264: false };
258 #[cfg_attr(not(test), allow(dead_code))]
260 pub(crate) const ALL: CodecSet = CodecSet { h264: true };
261
262 pub(crate) fn contains(self, codec: VideoCodec) -> bool {
264 match codec {
265 VideoCodec::Vp8 => true,
266 VideoCodec::H264 => self.h264,
267 }
268 }
269
270 pub(crate) fn codecs(self) -> Vec<VideoCodec> {
272 let mut v = vec![VideoCodec::Vp8];
273 if self.h264 {
274 v.push(VideoCodec::H264);
275 }
276 v
277 }
278
279 pub(crate) fn negotiated(
288 cfg_h264: bool,
289 declared: Option<&[VideoCodec]>,
290 pref: VideoCodecPreference,
291 ) -> CodecSet {
292 let declared_ok = match declared {
293 None => true,
294 Some(d) => !cfg!(target_os = "linux") && d.contains(&VideoCodec::H264),
295 };
296 CodecSet {
297 h264: cfg_h264 && pref != VideoCodecPreference::PreferVp8 && declared_ok,
298 }
299 }
300}
301
302#[derive(Debug, Default)]
305pub(crate) struct CodecSettings {
306 pref: Mutex<VideoCodecPreference>,
307 decode: Mutex<Option<Vec<VideoCodec>>>,
308}
309
310fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
311 m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
312}
313
314impl CodecSettings {
315 pub(crate) fn preference(&self) -> VideoCodecPreference {
316 *lock(&self.pref)
317 }
318
319 pub(crate) fn set_preference(&self, pref: VideoCodecPreference) {
320 *lock(&self.pref) = pref;
321 }
322
323 pub(crate) fn decode(&self) -> Option<Vec<VideoCodec>> {
324 lock(&self.decode).clone()
325 }
326
327 pub(crate) fn set_decode(&self, codecs: &[VideoCodec]) {
328 let mut v = codecs.to_vec();
329 v.sort_by_key(|c| c.as_str());
330 v.dedup();
331 *lock(&self.decode) = Some(v);
332 }
333
334 pub(crate) fn negotiated(&self, cfg_h264: bool) -> CodecSet {
336 CodecSet::negotiated(cfg_h264, self.decode().as_deref(), self.preference())
337 }
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343
344 const PREFS: [VideoCodecPreference; 3] = [
345 VideoCodecPreference::Automatic,
346 VideoCodecPreference::PreferH264,
347 VideoCodecPreference::PreferVp8,
348 ];
349 const DETECTIONS: [H264Detection; 4] = [
350 H264Detection::Usable,
351 H264Detection::NotDetected,
352 H264Detection::Unconfirmed,
353 H264Detection::NoPlatformCheck,
354 ];
355
356 #[test]
357 fn the_effective_codec_follows_the_table() {
358 use CodecPreferenceReason as R;
359 use H264Detection as D;
360 use VideoCodec::{H264, Vp8};
361 use VideoCodecPreference as P;
362 let want = [
363 (P::Automatic, D::Usable, (H264, None)),
364 (P::Automatic, D::NotDetected, (Vp8, None)),
365 (P::Automatic, D::Unconfirmed, (Vp8, None)),
366 (P::Automatic, D::NoPlatformCheck, (Vp8, None)),
367 (P::PreferH264, D::Usable, (H264, None)),
368 (P::PreferH264, D::NotDetected, (Vp8, Some(R::NotDetected))),
369 (P::PreferH264, D::Unconfirmed, (Vp8, Some(R::Platform))),
370 (P::PreferH264, D::NoPlatformCheck, (Vp8, Some(R::Platform))),
371 (P::PreferVp8, D::Usable, (Vp8, None)),
372 (P::PreferVp8, D::NotDetected, (Vp8, None)),
373 (P::PreferVp8, D::Unconfirmed, (Vp8, None)),
374 (P::PreferVp8, D::NoPlatformCheck, (Vp8, None)),
375 ];
376 assert_eq!(want.len(), PREFS.len() * DETECTIONS.len());
377 for (p, d, out) in want {
378 assert_eq!(effective_publish_codec(p, d), out, "{p:?} {d:?}");
379 assert_eq!(effective_publish_codec_under_policy(p, d, true), out);
381 }
382 assert_eq!(
384 effective_publish_codec_under_policy(P::PreferH264, D::Usable, false),
385 (Vp8, Some(R::Policy))
386 );
387 assert_eq!(
388 effective_publish_codec_under_policy(P::Automatic, D::Usable, false),
389 (Vp8, None)
390 );
391 assert_eq!(
393 effective_publish_codec_under_policy(P::PreferH264, D::NoPlatformCheck, false),
394 (Vp8, Some(R::Platform))
395 );
396 }
397
398 #[test]
399 fn h264_is_published_only_when_detected() {
400 for p in PREFS {
401 for d in DETECTIONS {
402 let (codec, _) = effective_publish_codec(p, d);
403 if codec == VideoCodec::H264 {
404 assert!(d.is_usable(), "{p:?} {d:?}");
405 assert_ne!(p, VideoCodecPreference::PreferVp8);
406 }
407 }
408 }
409 }
410
411 #[test]
412 fn the_preference_names_round_trip() {
413 for p in PREFS {
414 assert_eq!(VideoCodecPreference::from_name(p.as_str()), Some(p));
415 let json = serde_json::to_string(&p).unwrap_or_default();
416 assert_eq!(json, format!("\"{}\"", p.as_str()));
417 }
418 assert_eq!(VideoCodecPreference::from_name("h264"), None);
419 assert_eq!(
420 VideoCodecPreference::default(),
421 VideoCodecPreference::Automatic
422 );
423 for r in [
424 CodecPreferenceReason::NotDetected,
425 CodecPreferenceReason::Platform,
426 CodecPreferenceReason::Policy,
427 ] {
428 let json = serde_json::to_string(&r).unwrap_or_default();
429 assert_eq!(json, format!("\"{}\"", r.as_str()));
430 }
431 }
432
433 #[cfg(feature = "video-core")]
434 #[test]
435 fn ios_versions() {
436 assert!(ios_before_17_4("iOS Version 17.2 (Build 21C62)"));
437 assert!(ios_before_17_4("iOS Version 16.7.8 (Build 20H343)"));
438 assert!(ios_before_17_4("iOS 17"));
439 assert!(!ios_before_17_4("iOS Version 17.4 (Build 21E219)"));
440 assert!(!ios_before_17_4("iOS Version 18.1 (Build 22B83)"));
441 assert!(!ios_before_17_4("macOS Version 14.2 (Build 23C64)"));
442 assert!(!ios_before_17_4("iOS"));
443 assert!(!ios_before_17_4("fake"));
444 }
445
446 #[test]
447 fn prefer_vp8_and_a_declaration_without_h264_offer_vp8_only() {
448 use VideoCodec::{H264, Vp8};
449 for p in PREFS {
450 assert_eq!(
451 CodecSet::negotiated(false, None, p),
452 CodecSet::VP8_ONLY,
453 "{p:?}"
454 );
455 assert_eq!(
456 CodecSet::negotiated(true, Some(&[Vp8][..]), p),
457 CodecSet::VP8_ONLY
458 );
459 assert_eq!(
460 CodecSet::negotiated(true, Some(&[][..]), p),
461 CodecSet::VP8_ONLY
462 );
463 }
464 for declared in [None, Some(&[Vp8, H264][..])] {
465 assert_eq!(
466 CodecSet::negotiated(true, declared, VideoCodecPreference::PreferVp8),
467 CodecSet::VP8_ONLY
468 );
469 }
470 assert_eq!(
472 CodecSet::negotiated(true, None, VideoCodecPreference::Automatic),
473 CodecSet::ALL
474 );
475 assert!(CodecSet::VP8_ONLY.contains(Vp8));
476 assert!(!CodecSet::VP8_ONLY.contains(H264));
477 assert_eq!(CodecSet::ALL.codecs(), vec![Vp8, H264]);
478 }
479
480 #[cfg(target_os = "linux")]
482 #[test]
483 fn linux_never_offers_h264_once_declared() {
484 use VideoCodec::{H264, Vp8};
485 for p in PREFS {
486 for cfg_h264 in [false, true] {
487 for declared in [&[][..], &[Vp8][..], &[H264][..], &[Vp8, H264][..]] {
488 let set = CodecSet::negotiated(cfg_h264, Some(declared), p);
489 assert!(!set.contains(H264), "{p:?} {cfg_h264} {declared:?}");
490 assert!(set.contains(Vp8));
491 }
492 }
493 let cfg = crate::ClientConfig::new("t", std::env::temp_dir());
495 assert!(!CodecSet::negotiated(cfg.video_h264, None, p).contains(H264));
496 }
497 let s = CodecSettings::default();
498 s.set_decode(&[H264, Vp8, H264]);
499 assert_eq!(s.decode(), Some(vec![H264, Vp8]));
500 assert!(!s.negotiated(true).contains(H264));
501 }
502
503 #[cfg(not(target_os = "linux"))]
504 #[test]
505 fn a_declared_h264_decoder_is_offered() {
506 use VideoCodec::{H264, Vp8};
507 let s = CodecSettings::default();
508 assert_eq!(s.negotiated(true), CodecSet::ALL);
509 s.set_decode(&[Vp8]);
510 assert_eq!(s.negotiated(true), CodecSet::VP8_ONLY);
511 s.set_decode(&[Vp8, H264]);
512 assert_eq!(s.negotiated(true), CodecSet::ALL);
513 assert_eq!(s.negotiated(false), CodecSet::VP8_ONLY);
514 s.set_preference(VideoCodecPreference::PreferVp8);
515 assert_eq!(s.negotiated(true), CodecSet::VP8_ONLY);
516 }
517
518 #[cfg(feature = "video-core")]
519 #[test]
520 fn detection_from_capabilities() {
521 use kessel_video::{Capabilities, CodecCapability, CodecDirection, Implementation};
522 let entry = |dir, imp| {
523 CodecCapability::new(
524 kessel_video::VideoCodec::H264,
525 dir,
526 imp,
527 "t",
528 1920,
529 1080,
530 30,
531 )
532 };
533 let caps = |backend: &'static str, os: &str, entries: Vec<CodecCapability>| {
534 let mut c = Capabilities::new(backend, os);
535 c.codecs = entries;
536 c
537 };
538 let hw = || entry(CodecDirection::Encode, Implementation::Hardware);
539 let sw = || entry(CodecDirection::Encode, Implementation::Software);
540 let dec = || entry(CodecDirection::Decode, Implementation::Hardware);
541 let mac = "macOS Version 14.2 (Build 23C64)";
542 assert_eq!(
543 h264_encode_detection(&caps("apple", mac, vec![hw(), sw(), dec()])),
544 H264Detection::Usable
545 );
546 assert_eq!(
548 h264_encode_detection(&caps("apple", mac, vec![sw(), dec()])),
549 H264Detection::NotDetected
550 );
551 assert_eq!(
552 h264_encode_detection(&caps(
553 "apple",
554 "iOS Version 17.2 (Build 21C62)",
555 vec![dec()]
556 )),
557 H264Detection::Unconfirmed
558 );
559 assert_eq!(
560 h264_encode_detection(&caps(
561 "apple",
562 "iOS Version 17.5 (Build 21F79)",
563 vec![dec()]
564 )),
565 H264Detection::NotDetected
566 );
567 for b in NO_H264_BACKENDS {
569 assert_eq!(
570 h264_encode_detection(&caps(b, "x", vec![hw()])),
571 H264Detection::NoPlatformCheck,
572 "{b}"
573 );
574 }
575 assert_eq!(
577 h264_encode_detection(&caps("fixture", "fixture", vec![hw()])),
578 H264Detection::Usable
579 );
580 assert_eq!(
581 H264Detection::from_session(Implementation::Hardware),
582 H264Detection::Usable
583 );
584 assert_eq!(
585 H264Detection::from_session(Implementation::Software),
586 H264Detection::NotDetected
587 );
588 assert_eq!(
589 H264Detection::from_session(Implementation::Unknown),
590 H264Detection::Unconfirmed
591 );
592 }
593}