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