alhazen-core 0.6.0

Native media engine for Rust: plays video and audio from files and HTTP, with pure-Rust and OS (GPU) decoders. UI-agnostic.
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
//! `HlsDemuxer`: plays an HLS presentation through the ordinary `Demuxer` interface. The main
//! playlist (a variant) and, when the variant's audio is separate, an audio rendition are fetched
//! by one `Track` each; their packets are mapped onto one timeline and returned in time order.

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use crossbeam_channel::Sender;
use url::Url;

use super::abr::Abr;
use super::http::Fetcher;
use super::playlist::{self, Playlist, Rendition, VariantStream};
use super::segment::SegmentDemuxer;
use super::timeline::{Role, Timeline};
use super::track::{SegmentData, Start, Track, TrackConfig, TrackEvent};
use crate::backend::Registry;
use crate::demux::{Codec, Demuxer, Packet, StreamInfo, StreamKind};
use crate::player::PlayerEvent;
use crate::{Error, Result};

const VIDEO_ID: u32 = 1;
const AUDIO_ID: u32 = 2;
const POLL: Duration = Duration::from_millis(50);

/// One variant of an HLS presentation, as offered to the user.
#[derive(Clone, Debug, PartialEq)]
pub struct VariantInfo {
    /// Peak bits per second.
    pub bandwidth: u64,
    pub resolution: Option<(u32, u32)>,
    pub codecs: Vec<String>,
    pub frame_rate: Option<f64>,
}

/// Which variant to play.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Variant {
    /// Adaptive bitrate: chosen from measured throughput.
    Auto,
    /// This one (an index into `variants()`), until `Auto` is chosen again.
    Index(usize),
}

/// An alternative audio track of an HLS presentation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AudioRendition {
    pub name: String,
    pub language: Option<String>,
}

/// What the application can see and steer while an HLS demuxer runs (shared with the player).
pub struct HlsControl {
    variants: Vec<VariantInfo>,
    renditions: Vec<AudioRendition>,
    current: AtomicUsize,
    requested: Mutex<Option<Variant>>,
    requested_audio: Mutex<Option<usize>>,
    /// Where `VariantChanged` goes (the player's event channel).
    events: Mutex<Option<Sender<PlayerEvent>>>,
    /// The player is going away: stop waiting for downloads.
    shutdown: AtomicBool,
}

impl HlsControl {
    pub fn variants(&self) -> Vec<VariantInfo> {
        self.variants.clone()
    }

    /// The variant being played (index into `variants()`).
    pub fn current_variant(&self) -> usize {
        self.current.load(Ordering::Relaxed)
    }

    pub fn set_variant(&self, v: Variant) {
        *self.requested.lock().unwrap() = Some(v);
    }

    /// The audio renditions of the variant being played (empty when its audio is muxed in).
    pub fn audio_renditions(&self) -> Vec<AudioRendition> {
        self.renditions.clone()
    }

    /// Switches to another of `audio_renditions()`.
    pub fn set_audio_rendition(&self, index: usize) {
        *self.requested_audio.lock().unwrap() = Some(index);
    }

    pub(crate) fn set_events(&self, events: Sender<PlayerEvent>) {
        *self.events.lock().unwrap() = Some(events);
    }

    fn variant_changed(&self, variant: usize) {
        if self.current.swap(variant, Ordering::Relaxed) != variant
            && let Some(tx) = self.events.lock().unwrap().as_ref()
        {
            let _ = tx.send(PlayerEvent::VariantChanged(variant));
        }
    }

    pub(crate) fn shut_down(&self) {
        self.shutdown.store(true, Ordering::Relaxed);
    }
}

/// A packet ready to be returned.
struct Out {
    id: u32,
    pts: Duration,
    keyframe: bool,
    data: Vec<u8>,
    info: Arc<StreamInfo>,
}

/// The segment a lane is reading.
struct Open {
    demux: SegmentDemuxer,
    offset: i128,
    disc: u64,
}

/// One playlist's packets on their way out.
struct Lane {
    role: Role,
    track: Track,
    seg: Option<Open>,
    pending: Option<Out>,
    /// Current format of each kind of stream in this lane.
    formats: HashMap<StreamKind, Arc<StreamInfo>>,
    /// TS timestamp unwrapping reference, and the discontinuity sequence it belongs to.
    ts_ref: Option<(u64, u64)>,
    /// TS video parameter sets of the last segment, and its discontinuity sequence.
    ts_params: Option<(crate::demux::VideoParams, u64)>,
    ended: bool,
    /// Seeks sent to the track: older segments are dropped.
    epoch: u64,
    /// Main lane with a separate audio rendition: its own audio is dropped.
    use_audio: bool,
    /// After a seek: drop packets until a video keyframe.
    wait_key: bool,
    /// A new audio rendition: drop what comes before where the old one was.
    skip_before: Option<Duration>,
    /// Live: this lane jumped to the live edge because the other one did.
    jump_by_peer: bool,
    /// Live: this lane just jumped on its own; the other lane must follow.
    jumped: bool,
}

impl Lane {
    fn new(role: Role, track: Track, use_audio: bool) -> Self {
        Self { role, track, seg: None, pending: None, formats: HashMap::new(), ts_ref: None, ts_params: None, ended: false, epoch: 0, use_audio, wait_key: false, skip_before: None, jump_by_peer: false, jumped: false }
    }
}

/// Variant selection for the main lane.
struct Selection {
    abr: Abr,
    blacklist: Vec<bool>,
    /// The variant the track is fetching.
    fetching: usize,
    /// Chosen by the application (`Variant::Index`); `None`: ABR decides.
    manual: Option<usize>,
    /// Pts of the last main packet returned: the media buffered is from here to the end of the
    /// newest segment downloaded.
    returned: Duration,
}

impl Selection {
    /// After a main segment arrived: measure, then pick the variant to fetch next (`Some` when
    /// it differs from the one being fetched). `fetched_end`: where the newest downloaded segment
    /// ends.
    fn on_segment(&mut self, s: &SegmentData, control: &HlsControl, fetched_end: Duration) -> Option<usize> {
        if s.bytes > 0 {
            self.abr.sample(s.bytes, s.elapsed);
        }
        control.variant_changed(s.variant);
        let n = self.blacklist.len();
        match control.requested.lock().unwrap().take() {
            Some(Variant::Index(i)) if i < n && !self.blacklist[i] => self.manual = Some(i),
            Some(Variant::Index(i)) => log::warn!("HLS: variant {i} cannot be chosen"),
            Some(Variant::Auto) => self.manual = None,
            None => {}
        }
        let buffer = fetched_end.saturating_sub(self.returned);
        let next = match self.manual {
            Some(i) => i,
            None => self.abr.choose(self.fetching, buffer, s.duration, &self.blacklist),
        };
        if next == self.fetching {
            return None;
        }
        log::info!("HLS: switching to variant {next} (buffer {buffer:?}, estimate {:?} b/s)", self.abr.estimate());
        self.fetching = next;
        Some(next)
    }
}

pub struct HlsDemuxer {
    control: Arc<HlsControl>,
    main: Lane,
    audio: Option<Lane>,
    streams: Vec<StreamInfo>,
    timeline: Timeline,
    update: Option<StreamInfo>,
    /// The format last announced for each id.
    reported: HashMap<u32, Arc<StreamInfo>>,
    live: bool,
    duration: Option<Duration>,
    selection: Selection,
    /// Playlists of the current variant's audio renditions, and which one plays.
    /// `None`: that rendition is the audio muxed into the variant's own segments.
    rendition_uris: Vec<Option<Url>>,
    rendition: Option<usize>,
}

impl HlsDemuxer {
    /// Opens the playlist at `url` (master or media) and the first segments. `registry` decides
    /// which variants are playable.
    pub fn open(url: &Url, registry: &Registry) -> Result<HlsDemuxer> {
        // Each track has its own cancel flag: dropping one (a replaced audio rendition) must not
        // stop the others.
        let fetch = Fetcher::new(Arc::new(AtomicBool::new(false)));
        let first = fetch.get(url, None)?;
        let text = String::from_utf8_lossy(&first.data);
        let (variants, renditions) = match playlist::parse(&text, &first.url)? {
            Playlist::Media(_) => {
                let only = VariantStream {
                    uri: first.url.clone(),
                    bandwidth: 0,
                    average_bandwidth: None,
                    codecs: Vec::new(),
                    resolution: None,
                    frame_rate: None,
                    audio_group: None,
                };
                (vec![only], Vec::new())
            }
            Playlist::Master(m) => (m.variants, m.audio),
        };
        let mut blacklist: Vec<bool> = variants.iter().map(|v| !decodable(registry, &v.codecs)).collect();
        if blacklist.iter().all(|&b| b) {
            let mut codecs: Vec<String> = variants.iter().flat_map(|v| v.codecs.clone()).collect();
            codecs.sort();
            codecs.dedup();
            return Err(Error::UnsupportedCodec { codec: codecs.join(", "), tried_backends: registry.names() });
        }
        let bitrates: Vec<u64> = variants.iter().map(|v| v.bandwidth).collect();
        let playlists: Vec<Url> = variants.iter().map(|v| v.uri.clone()).collect();
        // The first variant whose playlist is playable (DRM-protected ones are left out).
        let (main, chosen) = loop {
            let chosen = Abr::initial(&bitrates, first.data.len() as u64, first.elapsed, &blacklist);
            let cfg = TrackConfig { playlists: playlists.clone(), variant: chosen, start: Start::LiveEdge, cancel: Arc::new(AtomicBool::new(false)) };
            match Track::start(cfg) {
                Ok(t) => break (t, chosen),
                Err(e @ Error::Unsupported(_)) => {
                    blacklist[chosen] = true;
                    if blacklist.iter().all(|&b| b) {
                        return Err(e);
                    }
                    log::warn!("HLS: variant {chosen} cannot be played ({e}); trying another");
                }
                Err(e) => return Err(e),
            }
        };
        let group: Vec<&Rendition> = match variants[chosen].audio_group.as_deref() {
            Some(g) => renditions.iter().filter(|r| r.group == g).collect(),
            None => Vec::new(),
        };
        let rendition = group.iter().position(|r| r.default).or((!group.is_empty()).then_some(0));
        let audio = match rendition.and_then(|i| group[i].uri.clone()) {
            Some(uri) => {
                let cfg = TrackConfig { playlists: vec![uri], variant: 0, start: Start::LiveEdge, cancel: Arc::new(AtomicBool::new(false)) };
                Some(Lane::new(Role::Audio, Track::start(cfg)?, true))
            }
            None => None,
        };
        let live = main.is_live();
        let duration = main.duration();
        let tolerance = Duration::from_secs(1).max(main.target_duration() * 2);
        let control = Arc::new(HlsControl {
            variants: variants
                .iter()
                .map(|v| VariantInfo { bandwidth: v.bandwidth, resolution: v.resolution, codecs: v.codecs.clone(), frame_rate: v.frame_rate })
                .collect(),
            renditions: group.iter().map(|r| AudioRendition { name: r.name.clone(), language: r.language.clone() }).collect(),
            current: AtomicUsize::new(chosen),
            requested: Mutex::new(None),
            requested_audio: Mutex::new(None),
            events: Mutex::new(None),
            shutdown: AtomicBool::new(false),
        });
        let rendition_uris = group.iter().map(|r| r.uri.clone()).collect();
        let mut d = HlsDemuxer {
            control,
            main: Lane::new(Role::Main, main, audio.is_none()),
            audio,
            streams: Vec::new(),
            timeline: Timeline::new(tolerance),
            update: None,
            reported: HashMap::new(),
            live,
            duration,
            selection: Selection {
                abr: Abr::new(bitrates),
                blacklist,
                fetching: chosen,
                manual: None,
                returned: Duration::ZERO,
            },
            rendition_uris,
            rendition,
        };
        d.fill_all()?;
        let video = d.main.formats.get(&StreamKind::Video).cloned();
        let audio = match &d.audio {
            Some(a) => a.formats.get(&StreamKind::Audio).cloned(),
            None => d.main.formats.get(&StreamKind::Audio).cloned(),
        };
        for (id, info) in [(VIDEO_ID, video), (AUDIO_ID, audio)] {
            if let Some(info) = info {
                d.reported.insert(id, info.clone());
                let mut s = (*info).clone();
                s.id = id;
                s.duration = duration;
                d.streams.push(s);
            }
        }
        if d.streams.is_empty() {
            return Err(Error::Demux("HLS stream without audio or video".into()));
        }
        Ok(d)
    }

    /// Steering and information for the application.
    pub fn control(&self) -> Arc<HlsControl> {
        self.control.clone()
    }

    /// Live streams have no duration and cannot seek.
    pub fn is_live(&self) -> bool {
        self.live
    }

    fn fill_all(&mut self) -> Result<()> {
        Self::fill(&mut self.main, &mut self.timeline, &self.control, Some(&mut self.selection))?;
        if std::mem::take(&mut self.main.jumped)
            && let Some(a) = self.audio.as_mut()
        {
            Self::follow_jump(a);
        }
        if let Some(a) = self.audio.as_mut() {
            Self::fill(a, &mut self.timeline, &self.control, None)?;
            if std::mem::take(&mut a.jumped) {
                Self::follow_jump(&mut self.main);
                Self::fill(&mut self.main, &mut self.timeline, &self.control, Some(&mut self.selection))?;
            }
        }
        Ok(())
    }

    /// The other playlist jumped to the live edge: this one goes there too, so both stay in sync.
    fn follow_jump(lane: &mut Lane) {
        lane.track.jump_to_live_edge();
        lane.epoch += 1;
        lane.seg = None;
        lane.pending = None;
        lane.ended = false;
        lane.ts_ref = None;
        lane.jump_by_peer = true;
    }

    /// Applies an audio rendition change the application asked for: a new audio lane from where
    /// the audio is now.
    fn switch_rendition(&mut self) -> Result<()> {
        let Some(i) = self.control.requested_audio.lock().unwrap().take() else { return Ok(()) };
        if Some(i) == self.rendition || i >= self.rendition_uris.len() {
            return Ok(());
        }
        self.rendition = Some(i);
        let Some(uri) = self.rendition_uris[i].clone() else {
            // The variant's own audio: no separate playlist.
            self.audio = None;
            self.main.use_audio = true;
            return Ok(());
        };
        let now = self.audio.as_ref().and_then(|a| a.pending.as_ref()).map_or(self.selection.returned, |p| p.pts);
        let start = if self.live { Start::LiveEdge } else { Start::At(now) };
        let cfg = TrackConfig { playlists: vec![uri], variant: 0, start, cancel: Arc::new(AtomicBool::new(false)) };
        let track = Track::start(cfg)?;
        self.timeline.forget(Role::Audio);
        let mut lane = Lane::new(Role::Audio, track, true);
        // Nothing before where the old rendition was.
        lane.skip_before = Some(now);
        self.audio = Some(lane);
        self.main.use_audio = false;
        Ok(())
    }

    /// Makes `lane.pending` hold the lane's next packet, unless the lane has ended.
    fn fill(lane: &mut Lane, timeline: &mut Timeline, control: &HlsControl, mut selection: Option<&mut Selection>) -> Result<()> {
        while lane.pending.is_none() && !lane.ended {
            if control.shutdown.load(Ordering::Relaxed) {
                lane.ended = true;
                break;
            }
            if let Some(open) = lane.seg.as_mut() {
                let Some(raw) = open.demux.next()? else {
                    // The next segment unwraps its TS timestamps from where this one ended.
                    if let Some(r) = open.demux.ts_last_raw() {
                        lane.ts_ref = Some((r, open.disc));
                    }
                    if let Some(p) = open.demux.ts_video_params() {
                        lane.ts_params = Some((p, open.disc));
                    }
                    lane.seg = None;
                    continue;
                };
                if let Some(u) = open.demux.take_update() {
                    lane.formats.insert(u.kind, Arc::new(u));
                }
                let wanted = match raw.kind {
                    StreamKind::Video => lane.role == Role::Main,
                    StreamKind::Audio => lane.use_audio,
                    StreamKind::Other => false,
                };
                if !wanted {
                    continue;
                }
                if lane.wait_key {
                    if raw.kind != StreamKind::Video || !raw.keyframe {
                        continue;
                    }
                    lane.wait_key = false;
                }
                let (id, info) = match raw.kind {
                    StreamKind::Video => (VIDEO_ID, lane.formats[&StreamKind::Video].clone()),
                    _ => (AUDIO_ID, lane.formats[&StreamKind::Audio].clone()),
                };
                let pts = Timeline::map(open.offset, raw.raw);
                if lane.skip_before.is_some_and(|t| pts < t) {
                    continue;
                }
                lane.skip_before = None;
                lane.pending = Some(Out { id, pts, keyframe: raw.keyframe, data: raw.data, info });
                continue;
            }
            match lane.track.recv(POLL) {
                None => {}
                Some(TrackEvent::Segment(s)) if s.epoch < lane.epoch => {}
                Some(TrackEvent::Segment(s)) => {
                    if let Some(sel) = selection.as_deref_mut()
                        && let Some(v) = sel.on_segment(&s, control, lane.track.fetched_end())
                    {
                        lane.track.switch(v);
                    }
                    Self::open_segment(lane, timeline, s)?
                }
                Some(TrackEvent::End(epoch)) if epoch < lane.epoch => {}
                Some(TrackEvent::End(_)) => lane.ended = true,
                Some(TrackEvent::Failed(_, epoch)) if epoch < lane.epoch => {}
                Some(TrackEvent::Failed(e, _)) => return Err(e),
            }
        }
        Ok(())
    }

    fn open_segment(lane: &mut Lane, timeline: &mut Timeline, s: SegmentData) -> Result<()> {
        if s.jumped {
            lane.ts_ref = None;
        }
        // TS timestamps wrap every 26.5 hours: unwrap near the previous segment's, or (after a
        // seek) near where the timeline expects this segment to start.
        let reference = lane.ts_ref.filter(|&(_, disc)| disc == s.discontinuity_seq).map(|(r, _)| r).or_else(|| {
            let offset = timeline.offset(lane.role, s.discontinuity_seq)?;
            let raw = s.start.as_nanos() as i128 - offset;
            (raw >= 0).then(|| (raw * 90_000 / 1_000_000_000) as u64)
        });
        let params = lane.ts_params.clone().filter(|(_, disc)| *disc == s.discontinuity_seq).map(|(p, _)| p);
        let mut demux = match SegmentDemuxer::open_with(s.data, s.init.as_deref().map(Vec::as_slice), reference, params) {
            Ok(d) => d,
            Err(e) if lane.track.is_live() => {
                log::warn!("HLS: skipping segment {}: {e}", s.seq);
                return Ok(());
            }
            Err(e) => return Err(e),
        };
        for info in &demux.streams {
            lane.formats.insert(info.kind, Arc::new(info.clone()));
        }
        let first = demux.first_raw()?.unwrap_or_default();
        let offset = if !s.jumped {
            timeline.anchor(lane.role, s.discontinuity_seq, s.start, first)
        } else if std::mem::take(&mut lane.jump_by_peer) {
            // Following the other playlist: line up with its new offset.
            timeline.forget(lane.role);
            timeline.anchor(lane.role, s.discontinuity_seq, s.start, first)
        } else {
            lane.jumped = true;
            timeline.reanchor(lane.role, s.discontinuity_seq, s.start, first)
        };
        lane.seg = Some(Open { demux, offset, disc: s.discontinuity_seq });
        Ok(())
    }
}

impl Demuxer for HlsDemuxer {
    fn streams(&self) -> &[StreamInfo] {
        &self.streams
    }

    fn next_packet(&mut self) -> Result<Option<Packet>> {
        self.switch_rendition()?;
        self.fill_all()?;
        let take_audio = match (&self.main.pending, self.audio.as_ref().and_then(|a| a.pending.as_ref())) {
            (None, None) => return Ok(None),
            (Some(_), None) => false,
            (None, Some(_)) => true,
            (Some(m), Some(a)) => a.pts <= m.pts,
        };
        let out = if take_audio { self.audio.as_mut().unwrap().pending.take() } else { self.main.pending.take() }.unwrap();
        if !take_audio {
            self.selection.returned = out.pts;
        }
        let changed = self.reported.get(&out.id).is_none_or(|r| !same_format(r, &out.info));
        if changed {
            self.reported.insert(out.id, out.info.clone());
            let mut info = (*out.info).clone();
            info.id = out.id;
            info.duration = self.duration;
            if let Some(s) = self.streams.iter_mut().find(|s| s.id == out.id) {
                *s = info.clone();
            }
            self.update = Some(info);
        }
        Ok(Some(Packet { stream: out.id, pts: out.pts, keyframe: out.keyframe, data: out.data, generation: 0 }))
    }

    fn seek(&mut self, target: Duration) -> Result<Duration> {
        if self.live {
            return Err(Error::Seek("live HLS streams cannot seek".into()));
        }
        let has_video = self.streams.iter().any(|s| s.kind == StreamKind::Video);
        for lane in std::iter::once(&mut self.main).chain(self.audio.as_mut()) {
            lane.track.seek(target);
            lane.epoch += 1;
            lane.seg = None;
            lane.pending = None;
            lane.ended = false;
            lane.ts_ref = None;
        }
        self.main.wait_key = has_video;
        self.selection.returned = target;
        // A format change still on its way to a decoder is dropped with the other stale messages
        // of a seek: announce every format again so the decoders surely match the new packets.
        self.reported.clear();
        self.fill_all()?;
        Ok(self.main.pending.as_ref().or(self.audio.as_ref().and_then(|a| a.pending.as_ref())).map_or(target, |p| p.pts))
    }

    fn take_stream_update(&mut self) -> Option<StreamInfo> {
        self.update.take()
    }
}

/// Whether a decoder for `a` can go on with `b`.
fn same_format(a: &StreamInfo, b: &StreamInfo) -> bool {
    a.codec == b.codec
        && a.extradata == b.extradata
        && (a.width, a.height, a.sample_rate, a.channels) == (b.width, b.height, b.sample_rate, b.channels)
}

/// Whether every codec named in a variant's `CODECS` can be decoded (unknown names pass: the
/// segment will tell).
fn decodable(registry: &Registry, codecs: &[String]) -> bool {
    codecs.iter().all(|c| {
        let codec = Codec::from_mp4_codec_string(c);
        let kind = match codec {
            Codec::Av1 | Codec::Vp8 | Codec::Vp9 | Codec::H264 | Codec::Hevc | Codec::ProRes => StreamKind::Video,
            Codec::Other(_) => return true,
            _ => StreamKind::Audio,
        };
        registry.can_decode(&StreamInfo::new(0, kind, codec))
    })
}

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

    fn control(current: usize) -> HlsControl {
        HlsControl {
            variants: Vec::new(),
            renditions: Vec::new(),
            current: AtomicUsize::new(current),
            requested: Mutex::new(None),
            requested_audio: Mutex::new(None),
            events: Mutex::new(None),
            shutdown: AtomicBool::new(false),
        }
    }

    fn segment(seq: u64, variant: usize) -> SegmentData {
        SegmentData {
            seq,
            discontinuity_seq: 0,
            start: Duration::from_secs(seq),
            duration: Duration::from_secs(1),
            data: Vec::new(),
            init: None,
            variant,
            bytes: 125_000, // 10 Mb/s over 100 ms
            elapsed: Duration::from_millis(100),
            epoch: 0,
            jumped: false,
        }
    }

    #[test]
    fn switches_up_when_downloads_are_well_ahead_of_playback() {
        let mut sel = Selection {
            abr: Abr::new(vec![433_000, 143_000]),
            blacklist: vec![false; 2],
            fetching: 1,
            manual: None,
            returned: Duration::ZERO,
        };
        let c = control(1);
        assert_eq!(sel.on_segment(&segment(0, 1), &c, Duration::from_secs(4)), None, "one sample is not enough");
        assert_eq!(sel.on_segment(&segment(1, 1), &c, Duration::from_secs(4)), None);
        // A segment is opened when reading reaches it: the position read is its start (2 s), and
        // the downloads are three segments further (5 s). Three fast downloads: up.
        sel.returned = Duration::from_secs(2);
        assert_eq!(sel.on_segment(&segment(2, 1), &c, Duration::from_secs(5)), Some(0));
    }

    #[test]
    fn a_manual_choice_holds_until_auto() {
        let mut sel =
            Selection { abr: Abr::new(vec![433_000, 143_000]), blacklist: vec![false; 2], fetching: 0, manual: None, returned: Duration::ZERO };
        let c = control(0);
        c.set_variant(Variant::Index(1));
        assert_eq!(sel.on_segment(&segment(0, 0), &c, Duration::from_secs(4)), Some(1));
        for seq in 1..5 {
            sel.returned = Duration::from_secs(seq);
            assert_eq!(sel.on_segment(&segment(seq, 1), &c, Duration::from_secs(seq + 3)), None, "manual: no ABR");
        }
        c.set_variant(Variant::Auto);
        sel.returned = Duration::from_secs(5);
        assert_eq!(sel.on_segment(&segment(5, 1), &c, Duration::from_secs(8)), Some(0));
    }
}