Skip to main content

alpha2_container/matroska/
read.rs

1//! The Matroska and `WebM` demuxer.
2
3use std::collections::{BTreeMap, VecDeque};
4use std::io::{Read, Seek};
5
6use alpha2_time::{MediaTime, TICKS_PER_SECOND};
7use bytes::{Bytes, BytesMut};
8
9use super::block::{self, Block};
10use super::describe::{self, Described, Encoding, Entry, Timing, rescale};
11use super::ebml::{self, Children, Header, Span, Step, header_at, id, is_level1};
12use super::timing::{Clock, Raw};
13use crate::audio::Input;
14use crate::{
15    ContainerReader, DemuxError, MAX_TRACKS, Packet, Source, TrackId, TrackInfo, VideoCodec,
16};
17
18/// The largest level-1 element other than a Cluster read into memory.
19const MAX_HEADER_ELEMENT: u64 = 64 << 20;
20/// The largest block or block group read into memory.
21const MAX_BLOCK: u64 = 256 << 20;
22/// Packets waiting for a decode time beyond the deepest reordering (16 frames).
23const MAX_HELD: usize = 17;
24/// How far stream probing reads (`FFmpeg`'s default `probesize`).
25const PROBE_BYTES: u64 = 5_000_000;
26
27/// Reads Matroska and `WebM` files: their tracks and each track's packets, timed as `FFmpeg`'s
28/// Matroska demuxer and generic demuxing layer time them.
29///
30/// Timestamps are in the track's time base, `TimestampScale` nanoseconds (milliseconds by
31/// default). Decode times `FFmpeg` leaves unset (the first packets of a reordered H.264, HEVC or
32/// MPEG-4 Part 2 stream) are the next packet's decode time less the packet's duration.
33pub struct MatroskaReader {
34    input: Input,
35    segment: Segment,
36    tracks: Vec<TrackInfo>,
37    states: Vec<TrackState>,
38    /// Clusters seen so far: position and timestamp.
39    clusters: BTreeMap<u64, u64>,
40    /// `CuePoint`s: cluster position and cue time, both of any track.
41    cues: Vec<(u64, u64)>,
42}
43
44impl std::fmt::Debug for MatroskaReader {
45    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        formatter
47            .debug_struct("MatroskaReader")
48            .field("tracks", &self.tracks)
49            .finish_non_exhaustive()
50    }
51}
52
53#[derive(Clone, Copy, Debug)]
54struct Segment {
55    end: u64,
56    first_cluster: Option<u64>,
57    scale: u64,
58    duration: Option<MediaTime>,
59}
60
61/// Where a scan of blocks stands.
62#[derive(Clone, Copy, Debug)]
63struct Scan {
64    pos: u64,
65    cluster: Option<Cluster>,
66}
67
68#[derive(Clone, Copy, Debug)]
69struct Cluster {
70    /// Where its payload ends; `None` for an unknown size.
71    end: Option<u64>,
72    timestamp: u64,
73}
74
75/// A `SimpleBlock` or `BlockGroup` element found by a scan.
76#[derive(Clone, Copy, Debug)]
77struct Found {
78    /// The element's first byte, which names the block.
79    at: u64,
80    payload: u64,
81    size: u64,
82    group: bool,
83    cluster_timestamp: u64,
84}
85
86/// A seek's keyframe: the block (by position) and lace it is in, and its presentation time.
87type Landing = ((u64, usize), i64);
88
89/// A packet waiting to be handed out, with the block and lace it came from.
90struct Pending {
91    packet: Packet,
92    origin: (u64, usize),
93    has_dts: bool,
94}
95
96struct TrackState {
97    number: u64,
98    described: Described,
99    track_scale: f64,
100    /// The segment's `TimestampScale`, which turns a `DefaultDuration` into ticks.
101    segment_scale: u64,
102    default_duration: u64,
103    stripped: Bytes,
104    clock_start: Clock,
105    clock: Clock,
106    scan: Scan,
107    /// The block of the AAC frame `FFmpeg` times before its decoder knows the frame length.
108    first_block: Option<u64>,
109    /// Packets ready to hand out, and packets waiting for a later decode time.
110    ready: VecDeque<Pending>,
111    held: VecDeque<Pending>,
112    /// Packets before this block and lace are dropped (a seek target).
113    skip_until: Option<(u64, usize)>,
114    /// The block and lace of the track's first packet, once a scan from the start produced it.
115    first_packet: Option<(u64, usize)>,
116    /// Whether the track's scan started at the first cluster and has produced nothing yet.
117    from_start: bool,
118    ended: bool,
119}
120
121impl TrackState {
122    fn new(entry: &Entry, described: Described, segment: &Segment) -> Self {
123        let reordered = matches!(
124            described.info.video.as_ref().map(|video| video.codec),
125            Some(VideoCodec::H264 | VideoCodec::Hevc)
126        );
127        let clock = Clock::new(
128            described.timing.clone(),
129            described.intra,
130            described.decode_times,
131            reordered,
132            described.time_base,
133        );
134        Self {
135            number: entry.number,
136            described,
137            track_scale: if entry.track_scale < 0.01 || entry.track_scale.is_nan() {
138                1.0
139            } else {
140                entry.track_scale
141            },
142            segment_scale: segment.scale,
143            default_duration: entry.default_duration,
144            stripped: match &entry.encoding {
145                Encoding::Stripped(bytes) => bytes.clone(),
146                _ => Bytes::new(),
147            },
148            clock_start: clock.clone(),
149            clock,
150            scan: Scan {
151                pos: segment.first_cluster.unwrap_or(segment.end),
152                cluster: None,
153            },
154            first_block: None,
155            ready: VecDeque::new(),
156            held: VecDeque::new(),
157            skip_until: None,
158            first_packet: None,
159            from_start: true,
160            ended: false,
161        }
162    }
163
164    /// The packets `FFmpeg`'s stream probing reads of this track before it knows enough: the
165    /// frames its decoder takes to show a picture and settle the reorder depth, one for audio.
166    fn probe_packets(&self) -> usize {
167        match (&self.described.timing, &self.described.info.video) {
168            (Timing::Video { depth, .. }, Some(video)) => match video.codec {
169                VideoCodec::H264 if *depth == 0 => 8,
170                VideoCodec::H264 => depth + 2,
171                _ => depth + 1,
172            },
173            (_, None) if self.described.info.audio.is_some() => 1,
174            _ => 0,
175        }
176    }
177}
178
179fn invalid(reason: impl Into<String>) -> DemuxError {
180    DemuxError::Invalid(reason.into())
181}
182
183/// The payload of the element at `pos` with header `header`, at most `limit` bytes.
184fn load(input: &mut Input, pos: u64, header: Header, limit: u64) -> Result<Bytes, DemuxError> {
185    let size = header.size.unwrap_or(0);
186    if size > limit {
187        return Err(invalid(format!(
188            "a Matroska element of {size} bytes is larger than this layer reads"
189        )));
190    }
191    let start = pos + header.len as u64;
192    let available = input.len().saturating_sub(start).min(size);
193    let length = usize::try_from(available).map_err(|_| invalid("an element is too large"))?;
194    Ok(Bytes::copy_from_slice(input.exact(start, length)?))
195}
196
197/// The position of the next Cluster ID at or after `pos`, before `end`.
198fn resync(input: &mut Input, mut pos: u64, end: u64) -> Result<Option<u64>, DemuxError> {
199    const CLUSTER: [u8; 4] = [0x1f, 0x43, 0xb6, 0x75];
200    while pos < end {
201        let window = input.peek(pos, 1 << 16)?;
202        if window.len() < 4 {
203            return Ok(None);
204        }
205        if let Some(found) = window.windows(4).position(|bytes| bytes == CLUSTER) {
206            return Ok(Some(pos + found as u64));
207        }
208        pos += window.len() as u64 - 3;
209    }
210    Ok(None)
211}
212
213/// Reads the EBML header and returns where the Segment's payload starts and ends.
214fn open_segment(input: &mut Input) -> Result<(u64, u64), DemuxError> {
215    let Some(head) = header_at(input, 0)? else {
216        return Err(invalid("the file has no EBML header"));
217    };
218    if head.id != id::EBML {
219        return Err(invalid("the file has no EBML header"));
220    }
221    let body = load(input, 0, head, 1 << 16)?;
222    let mut doc_type = String::from("(none)");
223    let (mut read_version, mut max_size, mut max_id, mut doc_read) = (1, 8, 4, 1);
224    for (element, value) in Children::new(&body) {
225        let number = || ebml::uint(value).unwrap_or(0);
226        match element {
227            id::EBML_READ_VERSION => read_version = number(),
228            id::EBML_MAX_SIZE_LENGTH => max_size = number(),
229            id::EBML_MAX_ID_LENGTH => max_id = number(),
230            id::DOC_TYPE => doc_type = ebml::string(value),
231            id::DOC_TYPE_READ_VERSION => doc_read = number(),
232            _ => {}
233        }
234    }
235    if read_version > 1 || max_size > 8 || max_id > 4 || doc_read > 3 {
236        return Err(DemuxError::Unsupported(format!(
237            "EBML read version {read_version}, doc type {doc_type} version {doc_read} is not read"
238        )));
239    }
240    let mut pos = head.len as u64 + head.size.unwrap_or(0);
241    let file_len = input.len();
242    loop {
243        let Some(found) = header_at(input, pos)? else {
244            return Err(invalid("the file has no Matroska segment"));
245        };
246        let payload = pos + found.len as u64;
247        if found.id == id::SEGMENT {
248            let end = found
249                .size
250                .map_or(file_len, |size| payload.saturating_add(size).min(file_len));
251            return Ok((payload, end));
252        }
253        match found.size {
254            Some(size) => pos = payload.saturating_add(size),
255            None => return Err(invalid("the file has no Matroska segment")),
256        }
257    }
258}
259
260/// The level-1 elements the reader keeps.
261#[derive(Default)]
262struct Headers {
263    scale: Option<u64>,
264    duration: Option<f64>,
265    entries: Option<Vec<Entry>>,
266    /// The Tracks element holds more than [`MAX_TRACKS`] entries.
267    too_many_tracks: bool,
268    cues: Option<Vec<(u64, u64)>>,
269    seeks: Vec<(u32, u64)>,
270}
271
272impl Headers {
273    fn take(&mut self, element: u32, body: &[u8], start: u64) {
274        match element {
275            id::INFO if self.scale.is_none() => {
276                let mut scale = 1_000_000;
277                for (child, value) in Children::new(body) {
278                    match child {
279                        id::TIMESTAMP_SCALE => scale = ebml::uint(value).unwrap_or(0),
280                        id::DURATION => self.duration = ebml::float(value),
281                        _ => {}
282                    }
283                }
284                self.scale = Some(if scale == 0 { 1_000_000 } else { scale });
285            }
286            id::TRACKS if self.entries.is_none() => {
287                let mut entries = Vec::new();
288                let mut within = true;
289                for (_, entry) in Children::new(body).filter(|(child, _)| *child == id::TRACK_ENTRY)
290                {
291                    if entries.len() == MAX_TRACKS {
292                        within = false;
293                        break;
294                    }
295                    entries.push(describe::entry(entry));
296                }
297                self.too_many_tracks = !within;
298                self.entries = Some(entries);
299            }
300            id::CUES if self.cues.is_none() => self.cues = Some(cues(body, start)),
301            id::SEEK_HEAD => self.seeks.extend(seeks(body)),
302            _ => {}
303        }
304    }
305}
306
307/// The level-1 elements before the first Cluster, then those the `SeekHead`s point to that are
308/// still missing, and where the first Cluster is.
309fn read_headers(
310    input: &mut Input,
311    start: u64,
312    end: u64,
313) -> Result<(Headers, Option<u64>), DemuxError> {
314    let mut headers = Headers::default();
315    let mut first_cluster = None;
316    let mut pos = start;
317    while pos < end {
318        let Some(found) = header_at(input, pos)? else {
319            first_cluster = resync(input, pos + 1, end)?;
320            break;
321        };
322        if found.id == id::CLUSTER {
323            first_cluster = Some(pos);
324            break;
325        }
326        let Some(size) = found.size else {
327            break;
328        };
329        if matches!(found.id, id::INFO | id::TRACKS | id::CUES | id::SEEK_HEAD) {
330            let body = load(input, pos, found, MAX_HEADER_ELEMENT)?;
331            headers.take(found.id, &body, start);
332        }
333        pos = pos + found.len as u64 + size;
334    }
335    for (element, position) in std::mem::take(&mut headers.seeks) {
336        let missing = match element {
337            id::INFO => headers.scale.is_none(),
338            id::TRACKS => headers.entries.is_none(),
339            id::CUES => headers.cues.is_none(),
340            _ => false,
341        };
342        let at = start.saturating_add(position);
343        if !missing || at >= end {
344            continue;
345        }
346        if let Some(found) = header_at(input, at)?
347            && found.id == element
348            && found.size.is_some()
349        {
350            let body = load(input, at, found, MAX_HEADER_ELEMENT)?;
351            headers.take(element, &body, start);
352        }
353    }
354    Ok((headers, first_cluster))
355}
356
357fn seeks(body: &[u8]) -> Vec<(u32, u64)> {
358    Children::new(body)
359        .filter(|(element, _)| *element == id::SEEK)
360        .filter_map(|(_, seek)| {
361            let (mut target, mut position) = (None, None);
362            for (element, value) in Children::new(seek) {
363                match element {
364                    id::SEEK_ID => target = ebml::uint(value),
365                    id::SEEK_POSITION => position = ebml::uint(value),
366                    _ => {}
367                }
368            }
369            Some((u32::try_from(target?).ok()?, position?))
370        })
371        .collect()
372}
373
374/// The most cue positions kept; later ones are ignored, since cues only shorten seeks.
375const MAX_CUE_POSITIONS: usize = 1 << 20;
376
377fn cues(body: &[u8], start: u64) -> Vec<(u64, u64)> {
378    let mut found = Vec::new();
379    for (element, point) in Children::new(body) {
380        if found.len() >= MAX_CUE_POSITIONS {
381            break;
382        }
383        if element != id::CUE_POINT {
384            continue;
385        }
386        let mut time = 0;
387        let mut positions = Vec::new();
388        for (child, value) in Children::new(point) {
389            match child {
390                id::CUE_TIME => time = ebml::uint(value).unwrap_or(0),
391                id::CUE_TRACK_POSITIONS => {
392                    for (inner, number) in Children::new(value) {
393                        if inner == id::CUE_CLUSTER_POSITION
394                            && let Some(position) = ebml::uint(number)
395                        {
396                            positions.push(start.saturating_add(position));
397                        }
398                    }
399                }
400                _ => {}
401            }
402        }
403        let room = MAX_CUE_POSITIONS - found.len();
404        found.extend(
405            positions
406                .into_iter()
407                .take(room)
408                .map(|position| (position, time)),
409        );
410    }
411    found
412}
413
414/// The `Info` `Duration` of `duration` segment ticks of `scale` nanoseconds, truncated to whole
415/// microseconds as `FFmpeg` stores a file's duration, then rounded to ticks.
416fn segment_duration(duration: f64, scale: u64) -> Option<MediaTime> {
417    #[expect(
418        clippy::cast_precision_loss,
419        reason = "a timestamp scale is far below 2^52"
420    )]
421    let micros = (duration * scale as f64 / 1_000.0).trunc();
422    if !micros.is_finite() || micros <= 0.0 || micros >= 9.0e15 {
423        return None;
424    }
425    #[expect(
426        clippy::cast_possible_truncation,
427        reason = "whole and within range, checked above"
428    )]
429    let micros = micros as i64;
430    let ticks = (i128::from(micros) * i128::from(TICKS_PER_SECOND) + 500_000) / 1_000_000;
431    i64::try_from(ticks).ok().map(MediaTime::from_ticks)
432}
433
434impl MatroskaReader {
435    /// Opens the Matroska or `WebM` file at `path`.
436    ///
437    /// # Errors
438    /// A file that cannot be read, is not Matroska, or breaks this layer's limits.
439    pub fn open(path: &std::path::Path) -> Result<Self, DemuxError> {
440        Self::new(std::fs::File::open(path)?)
441    }
442
443    /// Reads a Matroska or `WebM` file from `source`.
444    ///
445    /// # Errors
446    /// A source that cannot be read, is not Matroska, or breaks this layer's limits.
447    pub fn new<R: Read + Seek + Send + 'static>(source: R) -> Result<Self, DemuxError> {
448        let source: Box<dyn Source> = Box::new(source);
449        let mut input = Input::new(source)?;
450        let (start, end) = open_segment(&mut input)?;
451        let (headers, first_cluster) = read_headers(&mut input, start, end)?;
452        let scale = headers.scale.unwrap_or(1_000_000);
453        let segment = Segment {
454            end,
455            first_cluster,
456            scale,
457            duration: headers
458                .duration
459                .and_then(|duration| segment_duration(duration, scale)),
460        };
461        let mut tracks = Vec::new();
462        let mut states = Vec::new();
463        if headers.too_many_tracks {
464            return Err(DemuxError::Invalid(
465                "the file has more tracks than this layer reads".into(),
466            ));
467        }
468        for entry in headers.entries.unwrap_or_default() {
469            if !describe::listed(&entry) {
470                continue;
471            }
472            let described = describe::describe(&entry, segment.scale)?;
473            tracks.push(described.info.clone());
474            states.push(TrackState::new(&entry, described, &segment));
475        }
476        let mut cues = headers.cues.unwrap_or_default();
477        cues.retain(|(position, _)| *position >= start && *position < end);
478        cues.sort_unstable();
479        cues.dedup();
480        let mut reader = Self {
481            input,
482            segment,
483            tracks,
484            states,
485            clusters: BTreeMap::new(),
486            cues,
487        };
488        reader.probe()?;
489        Ok(reader)
490    }
491
492    fn state(&self, track: TrackId) -> Result<usize, DemuxError> {
493        self.tracks
494            .iter()
495            .position(|info| info.id == track)
496            .ok_or(DemuxError::NoSuchTrack(track.0))
497    }
498
499    /// The next block element `scan` reaches, of any track.
500    fn next_block(&mut self, scan: &mut Scan) -> Result<Option<Found>, DemuxError> {
501        let segment_end = self.segment.end;
502        loop {
503            if let Some(cluster) = scan.cluster.as_mut() {
504                let mut walk = Span {
505                    pos: scan.pos,
506                    end: cluster.end.unwrap_or(segment_end),
507                };
508                let found = match walk.next(&mut self.input)? {
509                    Step::Element(found) => found,
510                    Step::End => {
511                        scan.pos = walk.end;
512                        scan.cluster = None;
513                        continue;
514                    }
515                    Step::Unreadable => {
516                        scan.cluster = None;
517                        match resync(&mut self.input, scan.pos + 1, segment_end)? {
518                            Some(next) => scan.pos = next,
519                            None => return Ok(None),
520                        }
521                        continue;
522                    }
523                };
524                if cluster.end.is_none() && is_level1(found.header.id) {
525                    scan.cluster = None;
526                    continue;
527                }
528                let Some(size) = found.header.size else {
529                    scan.cluster = None;
530                    match resync(&mut self.input, scan.pos + 1, segment_end)? {
531                        Some(next) => scan.pos = next,
532                        None => return Ok(None),
533                    }
534                    continue;
535                };
536                if found.payload.saturating_add(size) > self.input.len() {
537                    scan.pos = segment_end;
538                    scan.cluster = None;
539                    return Ok(None);
540                }
541                scan.pos = walk.pos;
542                match found.header.id {
543                    id::CLUSTER_TIMESTAMP => {
544                        let bytes = load(&mut self.input, found.at, found.header, 8)?;
545                        cluster.timestamp = ebml::uint(&bytes).unwrap_or(0);
546                    }
547                    id::SIMPLE_BLOCK | id::BLOCK_GROUP => {
548                        return Ok(Some(Found {
549                            at: found.at,
550                            payload: found.payload,
551                            size: found.size,
552                            group: found.header.id == id::BLOCK_GROUP,
553                            cluster_timestamp: cluster.timestamp,
554                        }));
555                    }
556                    _ => {}
557                }
558            } else {
559                if scan.pos >= segment_end {
560                    return Ok(None);
561                }
562                let Some(found) = header_at(&mut self.input, scan.pos)? else {
563                    match resync(&mut self.input, scan.pos + 1, segment_end)? {
564                        Some(next) => scan.pos = next,
565                        None => return Ok(None),
566                    }
567                    continue;
568                };
569                let payload = scan.pos + found.len as u64;
570                if found.id == id::CLUSTER {
571                    let end = found
572                        .size
573                        .map(|size| payload.saturating_add(size).min(segment_end));
574                    let timestamp = self.cluster_timestamp(payload, end)?;
575                    self.clusters.insert(scan.pos, timestamp);
576                    scan.cluster = Some(Cluster { end, timestamp });
577                    scan.pos = payload;
578                    continue;
579                }
580                match found.size {
581                    Some(size) => scan.pos = payload.saturating_add(size),
582                    None => return Ok(None),
583                }
584            }
585        }
586    }
587
588    /// The timestamp of the cluster whose payload starts at `payload`, from its elements before
589    /// the first block (0 without one, as `FFmpeg` defaults it).
590    fn cluster_timestamp(&mut self, payload: u64, end: Option<u64>) -> Result<u64, DemuxError> {
591        let mut span = Span {
592            pos: payload,
593            end: end.unwrap_or(self.segment.end),
594        };
595        while let Step::Element(found) = span.next(&mut self.input)? {
596            match (found.header.id, found.header.size) {
597                (id::CLUSTER_TIMESTAMP, Some(_)) => {
598                    let bytes = load(&mut self.input, found.at, found.header, 8)?;
599                    return Ok(ebml::uint(&bytes).unwrap_or(0));
600                }
601                (id::SIMPLE_BLOCK | id::BLOCK_GROUP, _) | (_, None) => break,
602                (element, Some(_)) if is_level1(element) => break,
603                _ => {}
604            }
605        }
606        Ok(0)
607    }
608
609    /// The track number and frame count of the block element `found`.
610    fn block_head(&mut self, found: &Found) -> Result<Option<(u64, usize)>, DemuxError> {
611        if !found.group {
612            return Ok(block::head(self.input.peek(found.payload, 16)?));
613        }
614        let mut span = Span {
615            pos: found.payload,
616            end: found.payload + found.size,
617        };
618        while let Step::Element(child) = span.next(&mut self.input)? {
619            if child.header.id == id::BLOCK {
620                return Ok(block::head(self.input.peek(child.payload, 16)?));
621            }
622        }
623        Ok(None)
624    }
625
626    /// The next block of the track at `index` after `scan`, read whole.
627    fn next_track_block(
628        &mut self,
629        index: usize,
630        scan: &mut Scan,
631    ) -> Result<Option<(Found, Block)>, DemuxError> {
632        let number = self.states[index].number;
633        while let Some(found) = self.next_block(scan)? {
634            if self.block_head(&found)?.map(|(track, _)| track) != Some(number) {
635                continue;
636            }
637            if found.size > MAX_BLOCK {
638                return Err(invalid(format!(
639                    "a Matroska block of {} bytes is larger than this layer reads",
640                    found.size
641                )));
642            }
643            let length =
644                usize::try_from(found.size).map_err(|_| invalid("a block is too large"))?;
645            let data = Bytes::copy_from_slice(self.input.exact(found.payload, length)?);
646            if let Some(parsed) = block::parse(&data, found.group)?
647                && parsed.track == number
648            {
649                return Ok(Some((found, parsed)));
650            }
651        }
652        Ok(None)
653    }
654
655    /// The packets of `block`, timed by `clock`.
656    fn packets_of(
657        state: &TrackState,
658        clock: &mut Clock,
659        found: &Found,
660        block: &Block,
661        first: bool,
662    ) -> Vec<Pending> {
663        let described = &state.described;
664        let (num, _) = described.time_base;
665        let scale = i64::try_from(num).unwrap_or(1);
666        let relative = i64::from(block.relative);
667        let mut timecode = (relative >= 0 || found.cluster_timestamp >= relative.unsigned_abs())
668            .then(|| {
669                #[allow(
670                    clippy::cast_precision_loss,
671                    clippy::cast_possible_truncation,
672                    clippy::cast_sign_loss
673                )]
674                let cluster = (found.cluster_timestamp as f64 / state.track_scale) as u64;
675                #[allow(clippy::cast_sign_loss, clippy::cast_possible_wrap)]
676                let time = cluster
677                    .wrapping_add(relative as u64)
678                    .wrapping_sub(described.delay as u64) as i64;
679                time
680            });
681        let laces = block.frames.len() as u64;
682        let mut duration = block.duration;
683        if duration == 0 && state.default_duration != 0 {
684            duration = state
685                .default_duration
686                .saturating_mul(laces)
687                .checked_div(state.segment_scale)
688                .unwrap_or(0);
689        }
690        let rate = state
691            .described
692            .info
693            .audio
694            .as_ref()
695            .map_or(0, |audio| audio.sample_rate);
696        let discard = if block.discard_padding == 0 {
697            (0, 0)
698        } else {
699            let samples = rescale(block.discard_padding, i64::from(rate), 1_000_000_000);
700            let clamp = |value: i64| u32::try_from(value.max(0)).unwrap_or(u32::MAX);
701            if samples > 0 {
702                (0, clamp(samples))
703            } else {
704                (clamp(samples.saturating_neg()), 0)
705            }
706        };
707        let mut out = Vec::with_capacity(block.frames.len());
708        for (lace, frame) in block.frames.iter().enumerate() {
709            let lace_u = lace as u64;
710            let lace_duration = (u128::from(duration) * u128::from(lace_u + 1) / u128::from(laces))
711                .saturating_sub(u128::from(duration) * u128::from(lace_u) / u128::from(laces));
712            let lace_duration = i64::try_from(lace_duration).unwrap_or(i64::MAX);
713            let data = if state.stripped.is_empty() {
714                frame.clone()
715            } else {
716                let mut joined = BytesMut::with_capacity(state.stripped.len() + frame.len());
717                joined.extend_from_slice(&state.stripped);
718                joined.extend_from_slice(frame);
719                joined.freeze()
720            };
721            let this_timecode = timecode;
722            timecode = timecode
723                .and_then(|time| (lace_duration != 0).then(|| time.wrapping_add(lace_duration)));
724            if data.is_empty() {
725                continue;
726            }
727            let times = clock.times(&Raw {
728                timecode: this_timecode,
729                duration: lace_duration,
730                keyframe: block.keyframe && lace == 0,
731                data: &data,
732                first: first && lace == 0,
733            });
734            let has_dts = times.dts.is_some();
735            let pts = times.pts.or(times.dts).unwrap_or(0);
736            out.push(Pending {
737                packet: Packet {
738                    track: state.described.info.id,
739                    pts: pts.saturating_mul(scale),
740                    dts: times.dts.unwrap_or(pts).saturating_mul(scale),
741                    duration: times.duration.saturating_mul(scale),
742                    keyframe: times.keyframe,
743                    data,
744                    discard,
745                },
746                origin: (found.at, lace),
747                has_dts,
748            });
749        }
750        out
751    }
752
753    /// Reads the next block of the track at `index` into its queues; false at its end.
754    fn advance(&mut self, index: usize) -> Result<bool, DemuxError> {
755        let mut scan = self.states[index].scan;
756        let next = self.next_track_block(index, &mut scan)?;
757        self.states[index].scan = scan;
758        let Some((found, block)) = next else {
759            let state = &mut self.states[index];
760            state.ended = true;
761            while let Some(mut pending) = state.held.pop_front() {
762                pending.packet.dts = pending.packet.pts;
763                state.ready.push_back(pending);
764            }
765            return Ok(false);
766        };
767        let first = self.is_first_block(index, found.at);
768        let state = &mut self.states[index];
769        let mut clock = state.clock.clone();
770        let produced = Self::packets_of(state, &mut clock, &found, &block, first);
771        state.clock = clock;
772        if state.from_start
773            && let Some(pending) = produced.first()
774        {
775            state.first_packet = state.first_packet.or(Some(pending.origin));
776            state.from_start = false;
777        }
778        for pending in produced {
779            if pending.has_dts {
780                let mut next_dts = pending.packet.dts;
781                for held in state.held.iter_mut().rev() {
782                    next_dts = next_dts.saturating_sub(held.packet.duration.max(1));
783                    held.packet.dts = next_dts;
784                }
785                state.ready.extend(state.held.drain(..));
786                state.ready.push_back(pending);
787            } else {
788                state.held.push_back(pending);
789                // Reordering never holds more back; a stream without timestamps does not wait.
790                if state.held.len() > MAX_HELD {
791                    for mut held in state.held.drain(..) {
792                        held.packet.dts = held.packet.pts;
793                        state.ready.push_back(held);
794                    }
795                }
796            }
797        }
798        Ok(true)
799    }
800
801    /// Rewinds the track at `index` to `pos` (a cluster or the first one) with a fresh clock.
802    fn restart(&mut self, index: usize, pos: u64, skip_until: Option<(u64, usize)>) {
803        let from_start = Some(pos) == self.segment.first_cluster;
804        let state = &mut self.states[index];
805        state.scan = Scan { pos, cluster: None };
806        state.clock = state.clock_start.clone();
807        state.ready.clear();
808        state.held.clear();
809        state.skip_until = skip_until;
810        state.from_start = from_start;
811        state.ended = false;
812    }
813
814    /// The next packet of the track at `index`, past any seek target's predecessors.
815    fn next_pending(&mut self, index: usize) -> Result<Option<Pending>, DemuxError> {
816        loop {
817            let state = &mut self.states[index];
818            if let Some(pending) = state.ready.pop_front() {
819                if let Some(target) = state.skip_until {
820                    if pending.origin != target {
821                        continue;
822                    }
823                    state.skip_until = None;
824                }
825                return Ok(Some(Self::with_codec_delay(state, pending)));
826            }
827            if state.ended || !self.advance(index)? {
828                let state = &mut self.states[index];
829                if state.ready.is_empty() {
830                    return Ok(None);
831                }
832            }
833        }
834    }
835
836    /// `pending` with the track's `CodecDelay` as its skip-samples when it is the track's first
837    /// packet, as `FFmpeg` marks the first packet it reads of a track with an initial padding.
838    fn with_codec_delay(state: &TrackState, mut pending: Pending) -> Pending {
839        let priming = state
840            .described
841            .info
842            .audio
843            .as_ref()
844            .map_or(0, |audio| audio.priming);
845        if priming > 0 && state.first_packet == Some(pending.origin) {
846            pending.packet.discard.0 = priming;
847        }
848        pending
849    }
850
851    /// Cluster positions a seek may start from, with their time in the track's units.
852    fn seek_starts(&mut self, index: usize, target: i64) -> Result<Vec<(u64, i64)>, DemuxError> {
853        let Some(first) = self.segment.first_cluster else {
854            return Ok(Vec::new());
855        };
856        self.discover_clusters(index, target)?;
857        let state = &self.states[index];
858        let scale = i64::try_from(state.described.time_base.0).unwrap_or(1);
859        let time = |ticks: u64| -> i64 {
860            #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
861            let scaled = (ticks as f64 / state.track_scale) as i64;
862            scaled
863                .saturating_sub(state.described.delay)
864                .saturating_mul(scale)
865        };
866        let mut starts = vec![(first, i64::MIN)];
867        starts.extend(self.cues.iter().map(|(pos, ticks)| (*pos, time(*ticks))));
868        starts.extend(
869            self.clusters
870                .iter()
871                .map(|(pos, ticks)| (*pos, time(*ticks))),
872        );
873        starts.sort_unstable();
874        starts.dedup_by_key(|start| start.0);
875        Ok(starts)
876    }
877
878    /// Finds clusters past the last one seen, by their headers alone, until one starts after
879    /// `target` or one has no size.
880    fn discover_clusters(&mut self, index: usize, target: i64) -> Result<(), DemuxError> {
881        let state = &self.states[index];
882        let (track_scale, delay) = (state.track_scale, state.described.delay);
883        let scale = i64::try_from(state.described.time_base.0).unwrap_or(1);
884        let Some(mut pos) = self
885            .clusters
886            .last_key_value()
887            .map(|(pos, _)| *pos)
888            .or(self.segment.first_cluster)
889        else {
890            return Ok(());
891        };
892        while pos < self.segment.end {
893            let Some(found) = header_at(&mut self.input, pos)? else {
894                return Ok(());
895            };
896            let payload = pos + found.len as u64;
897            let Some(size) = found.size else {
898                return Ok(());
899            };
900            if found.id == id::CLUSTER {
901                let end = payload.saturating_add(size).min(self.segment.end);
902                let timestamp = self.cluster_timestamp(payload, Some(end))?;
903                self.clusters.insert(pos, timestamp);
904                #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
905                let time = ((timestamp as f64 / track_scale) as i64)
906                    .saturating_sub(delay)
907                    .saturating_mul(scale);
908                if time > target {
909                    return Ok(());
910                }
911            }
912            pos = payload.saturating_add(size);
913        }
914        Ok(())
915    }
916
917    /// The latest keyframe at or before `target` reached by reading from `pos` up to `stop`: its
918    /// block, lace and presentation time.
919    fn keyframe_from(
920        &mut self,
921        index: usize,
922        pos: u64,
923        target: i64,
924        stop: Option<u64>,
925    ) -> Result<Option<Landing>, DemuxError> {
926        let mut scan = Scan { pos, cluster: None };
927        let mut clock = self.states[index].clock_start.clone();
928        let mut best = None;
929        let mut from_start = Some(pos) == self.segment.first_cluster;
930        while let Some((found, block)) = self.next_track_block(index, &mut scan)? {
931            if stop.is_some_and(|stop| found.at >= stop) {
932                break;
933            }
934            let first = self.is_first_block(index, found.at);
935            let produced = Self::packets_of(&self.states[index], &mut clock, &found, &block, first);
936            let state = &mut self.states[index];
937            if from_start && let Some(pending) = produced.first() {
938                state.first_packet = state.first_packet.or(Some(pending.origin));
939                from_start = false;
940            }
941            for pending in produced {
942                if !pending.packet.keyframe {
943                    continue;
944                }
945                if pending.packet.pts > target {
946                    return Ok(best);
947                }
948                best = Some((pending.origin, pending.packet.pts));
949            }
950        }
951        Ok(best)
952    }
953
954    /// Whether the block at `at` holds the frame `FFmpeg` times before its decoder knows the
955    /// frame length (see [`Self::probe`]).
956    fn is_first_block(&self, index: usize, at: u64) -> bool {
957        self.states[index].first_block == Some(at)
958    }
959
960    /// Reads blocks in file order, as `FFmpeg`'s stream probing does, until every track has had
961    /// the packets probing waits for. An AAC track whose second packet comes later gets its first
962    /// packet handed out before the decoder told its frame length, so without a block duration
963    /// that packet has none.
964    fn probe(&mut self) -> Result<(), DemuxError> {
965        let aac = |state: &TrackState| matches!(state.described.timing, Timing::Aac { .. });
966        if !self.states.iter().any(aac) {
967            return Ok(());
968        }
969        let needs = self
970            .states
971            .iter()
972            .map(TrackState::probe_packets)
973            .collect::<Vec<_>>();
974        let mut counts = vec![0_usize; self.states.len()];
975        let mut first = vec![None; self.states.len()];
976        let start = self.segment.first_cluster.unwrap_or(self.segment.end);
977        let mut scan = Scan {
978            pos: start,
979            cluster: None,
980        };
981        while counts.iter().zip(&needs).any(|(count, need)| count < need) {
982            let Some(found) = self.next_block(&mut scan)? else {
983                break;
984            };
985            if found.at.saturating_sub(start) > PROBE_BYTES {
986                break;
987            }
988            let Some((number, laces)) = self.block_head(&found)? else {
989                continue;
990            };
991            if let Some(index) = self.states.iter().position(|state| state.number == number) {
992                first[index] = first[index].or(Some(found.at));
993                counts[index] += laces;
994            }
995        }
996        for (index, state) in self.states.iter_mut().enumerate() {
997            if aac(state) && counts[index] < 2 {
998                state.first_block = first[index];
999            }
1000        }
1001        Ok(())
1002    }
1003}
1004
1005impl ContainerReader for MatroskaReader {
1006    fn tracks(&self) -> &[TrackInfo] {
1007        &self.tracks
1008    }
1009
1010    fn file_duration(&self) -> Option<MediaTime> {
1011        self.segment.duration
1012    }
1013
1014    fn seek(&mut self, track: TrackId, pts: i64) -> Result<Option<i64>, DemuxError> {
1015        let index = self.state(track)?;
1016        let starts = self.seek_starts(index, pts)?;
1017        let begin = self.segment.first_cluster.unwrap_or(self.segment.end);
1018        let mut at = starts
1019            .iter()
1020            .rposition(|(_, time)| *time <= pts)
1021            .unwrap_or(0);
1022        // A retry stops where the attempt after it started: that one already read the rest and
1023        // found no keyframe at or before `pts`, so one seek reads the file at most once.
1024        let mut stop = None;
1025        while let Some(&(pos, _)) = starts.get(at) {
1026            if let Some((origin, found)) = self.keyframe_from(index, pos, pts, stop)? {
1027                self.restart(index, pos, Some(origin));
1028                return Ok(Some(found));
1029            }
1030            if at == 0 {
1031                break;
1032            }
1033            stop = Some(pos);
1034            at -= 1;
1035        }
1036        self.restart(index, begin, None);
1037        let first = self.next_pending(index)?;
1038        let state = &mut self.states[index];
1039        Ok(first.map(|pending| {
1040            let pts = pending.packet.pts;
1041            state.ready.push_front(pending);
1042            pts
1043        }))
1044    }
1045
1046    fn next_packet(&mut self, track: TrackId) -> Result<Option<Packet>, DemuxError> {
1047        let index = self.state(track)?;
1048        Ok(self.next_pending(index)?.map(|pending| pending.packet))
1049    }
1050}