1use std::{
8 collections::{BTreeMap, BTreeSet},
9 time::Instant,
10};
11
12use crate::{
13 NetworkSample,
14 bound::{Bound, Constraints, Rung},
15};
16
17#[derive(Debug, Clone, Default, PartialEq, Eq)]
19pub enum RenditionMode {
20 #[default]
24 Auto,
25 Pinned(String),
30 Off,
32}
33
34impl RenditionMode {
35 #[must_use]
37 pub fn pinned(name: impl Into<String>) -> Self {
38 Self::Pinned(name.into())
39 }
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum PinProblem {
45 Excluded(String),
49 Unknown(String),
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Choice {
56 pub rendition: Option<String>,
58 pub pin: Option<PinProblem>,
60}
61
62#[derive(Debug, Default)]
64pub struct Backoffs(BTreeMap<String, Instant>);
65
66impl Backoffs {
67 pub fn fail(&mut self, rendition: &str, until: Instant) {
69 self.0.insert(rendition.to_string(), until);
70 }
71
72 #[must_use]
74 pub fn excluded(&self, now: Instant) -> BTreeSet<String> {
75 self.0
76 .iter()
77 .filter(|(_, until)| **until > now)
78 .map(|(name, _)| name.clone())
79 .collect()
80 }
81
82 #[must_use]
84 pub fn is_excluded(&self, rendition: &str, now: Instant) -> bool {
85 self.0.get(rendition).is_some_and(|until| *until > now)
86 }
87
88 #[must_use]
90 pub fn any_excluded(&self, now: Instant) -> bool {
91 self.0.values().any(|until| *until > now)
92 }
93
94 pub fn clear(&mut self) {
96 self.0.clear();
97 }
98}
99
100#[must_use]
107#[allow(
108 clippy::too_many_arguments,
109 reason = "the rendition asked for and the one on screen are both weighed"
110)]
111pub fn choose(
112 mode: &RenditionMode,
113 rungs: &[Rung],
114 constraints: &Constraints,
115 current: Option<&str>,
116 on_screen: Option<&str>,
117 sample: Option<&NetworkSample>,
118 bound: &mut Bound,
119 now: Instant,
120) -> Choice {
121 let pin = match mode {
122 RenditionMode::Off => {
123 return Choice {
124 rendition: None,
125 pin: None,
126 };
127 }
128 RenditionMode::Pinned(name) => {
129 if constraints.excluded.contains(name) {
130 Some(PinProblem::Excluded(name.clone()))
131 } else if !rungs.iter().any(|rung| rung.name == *name) {
132 Some(PinProblem::Unknown(name.clone()))
133 } else {
134 return Choice {
135 rendition: Some(name.clone()),
136 pin: None,
137 };
138 }
139 }
140 RenditionMode::Auto => None,
141 };
142 let rendition = match sample {
143 Some(sample) => bound.decide(rungs, current, on_screen, constraints, sample, now),
144 None => best(rungs, constraints),
146 };
147 Choice { rendition, pin }
148}
149
150#[must_use]
152pub fn best(rungs: &[Rung], constraints: &Constraints) -> Option<String> {
153 rungs
154 .iter()
155 .find(|rung| constraints.allows(rung))
156 .or_else(|| rungs.last())
157 .map(|rung| rung.name.clone())
158}
159
160#[must_use]
167pub fn step_down(
168 mode: &RenditionMode,
169 rungs: &[Rung],
170 choice: Option<&str>,
171 on_screen: Option<&str>,
172) -> bool {
173 let rank = |name: &str| rungs.iter().position(|rung| rung.name == name);
174 matches!(mode, RenditionMode::Auto)
175 && match (choice, on_screen) {
176 (Some(choice), Some(playing)) => rank(choice) > rank(playing),
177 _ => false,
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184 use crate::Adaptation;
185
186 fn rung(name: &str, bitrate: u64) -> Rung {
187 Rung {
188 name: name.into(),
189 bitrate: Some(bitrate),
190 stalled: false,
191 }
192 }
193
194 fn ladder() -> Vec<Rung> {
195 vec![rung("1080p", 4_000_000), rung("360p", 500_000)]
196 }
197
198 fn pick(mode: &RenditionMode, excluded: &[&str]) -> Choice {
199 let constraints = Constraints {
200 excluded: excluded.iter().map(|name| name.to_string()).collect(),
201 };
202 let mut bound = Bound::new(Adaptation::default());
203 choose(
204 mode,
205 &ladder(),
206 &constraints,
207 None,
208 None,
209 None,
210 &mut bound,
211 Instant::now(),
212 )
213 }
214
215 #[test]
216 fn auto_without_signals_plays_the_best() {
217 assert_eq!(
218 pick(&RenditionMode::Auto, &[]).rendition.as_deref(),
219 Some("1080p")
220 );
221 }
222
223 #[test]
224 fn a_pin_plays_its_rendition() {
225 let choice = pick(&RenditionMode::Pinned("360p".into()), &[]);
226 assert_eq!(choice.rendition.as_deref(), Some("360p"));
227 assert_eq!(choice.pin, None);
228 }
229
230 #[test]
232 fn a_pin_to_a_missing_rendition_falls_back_and_says_why() {
233 let choice = pick(&RenditionMode::Pinned("4k".into()), &[]);
234 assert_eq!(choice.rendition.as_deref(), Some("1080p"));
235 assert_eq!(choice.pin, Some(PinProblem::Unknown("4k".into())));
236 }
237
238 #[test]
239 fn a_pin_to_a_failing_rendition_falls_back_until_it_is_retried() {
240 let choice = pick(&RenditionMode::Pinned("1080p".into()), &["1080p"]);
241 assert_eq!(choice.rendition.as_deref(), Some("360p"));
242 assert_eq!(choice.pin, Some(PinProblem::Excluded("1080p".into())));
243 }
244
245 #[test]
246 fn off_plays_nothing() {
247 assert_eq!(pick(&RenditionMode::Off, &[]).rendition, None);
248 }
249
250 #[test]
251 fn a_failing_rendition_is_skipped_by_auto() {
252 assert_eq!(
253 pick(&RenditionMode::Auto, &["1080p"]).rendition.as_deref(),
254 Some("360p")
255 );
256 }
257
258 #[test]
259 fn backoffs_expire() {
260 let now = Instant::now();
261 let mut backoffs = Backoffs::default();
262 assert!(!backoffs.any_excluded(now));
263 let until = now + std::time::Duration::from_secs(10);
264 backoffs.fail("1080p", until);
265 assert!(backoffs.is_excluded("1080p", now));
266 assert_eq!(backoffs.excluded(now).len(), 1);
267 assert!(!backoffs.is_excluded("1080p", until));
268 backoffs.clear();
269 assert!(!backoffs.any_excluded(now));
270 }
271
272 #[test]
273 fn step_down_needs_auto_and_a_lower_rung() {
274 let rungs = ladder();
275 assert!(step_down(
276 &RenditionMode::Auto,
277 &rungs,
278 Some("360p"),
279 Some("1080p")
280 ));
281 assert!(!step_down(
282 &RenditionMode::Auto,
283 &rungs,
284 Some("1080p"),
285 Some("360p")
286 ));
287 assert!(!step_down(&RenditionMode::Auto, &rungs, Some("360p"), None));
288 let pinned = RenditionMode::Pinned("360p".into());
289 assert!(!step_down(&pinned, &rungs, Some("360p"), Some("1080p")));
290 }
291
292 #[test]
293 fn the_default_mode_is_auto() {
294 assert_eq!(RenditionMode::default(), RenditionMode::Auto);
295 assert_eq!(
296 pick(&RenditionMode::default(), &[]).rendition.as_deref(),
297 Some("1080p")
298 );
299 assert_eq!(
300 RenditionMode::pinned("360p"),
301 RenditionMode::Pinned("360p".into())
302 );
303 }
304
305 #[test]
306 fn best_takes_the_first_allowed_rung_or_the_smallest() {
307 let ladder = ladder();
308 let none = Constraints::default();
309 assert_eq!(best(&ladder, &none).as_deref(), Some("1080p"));
310 let without_top = Constraints {
311 excluded: ["1080p".to_string()].into(),
312 };
313 assert_eq!(best(&ladder, &without_top).as_deref(), Some("360p"));
314 let without_any = Constraints {
315 excluded: ["1080p".to_string(), "360p".to_string()].into(),
316 };
317 assert_eq!(best(&ladder, &without_any).as_deref(), Some("360p"));
318 assert_eq!(best(&[], &none), None);
319 }
320}