aboutsummaryrefslogtreecommitdiff
path: root/remuxer/src/segment_extractor.rs
blob: 89d578402a800ff98155eb0d234ded79412f3f0e (plain)
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
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2024 metamuffin <metamuffin.org>
*/
use anyhow::{anyhow, bail, Result};
use jellymatroska::{block::Block, read::EbmlReader, unflatten::IterWithPos, Master, MatroskaTag};
use log::{debug, info, trace};

pub struct SegmentExtractIter<'a> {
    segment: &'a mut EbmlReader,
    extract: u64,
}

impl<'a> SegmentExtractIter<'a> {
    pub fn new(segment: &'a mut EbmlReader, extract: u64) -> Self {
        Self { segment, extract }
    }

    /// Returns the next block and sometimes its duration too.
    pub fn next(&mut self) -> Result<(Block, Option<u64>)> {
        let mut duration = None;
        let mut group = false;
        let mut saved_block = None;
        loop {
            let item = self.segment.next().ok_or(anyhow!("eof"))??;
            match item {
                MatroskaTag::Void(_) => (),
                MatroskaTag::Crc32(_) => (),
                MatroskaTag::Cluster(_) => (),
                MatroskaTag::Timestamp(_) => (),
                MatroskaTag::BlockGroup(Master::Start) => group = true,
                MatroskaTag::BlockGroup(Master::End) => {
                    if !group {
                        bail!("group end without start");
                    }
                    if let Some(block) = saved_block {
                        return Ok((block, duration));
                    }
                    group = false;
                }
                MatroskaTag::BlockDuration(d) => duration = Some(d),
                MatroskaTag::SimpleBlock(buf) | MatroskaTag::Block(buf) => {
                    let block = Block::parse(&buf)?;
                    if block.track == self.extract {
                        trace!("block: track={} tso={}", block.track, block.timestamp_off);
                        if group {
                            // can't return yet; there might be a BlockDuration coming
                            saved_block = Some(block);
                        } else {
                            return Ok((block, duration));
                        }
                    }
                }
                MatroskaTag::Cues(_) => bail!("reached cues, this is the end"),
                MatroskaTag::Segment(Master::End) => info!("extractor reached segment end"),
                _ => debug!("(rs) tag ignored: {item:?}"),
            }
        }
    }
}