aboutsummaryrefslogtreecommitdiff
path: root/remuxer/src/extract.rs
blob: bef5d4d4d15920c7f848ab3c1404fe0c5e86ec9d (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
/*
    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 crate::seek_index::get_seek_index;
use anyhow::{anyhow, bail};
use jellycommon::LocalTrack;
use jellymatroska::{block::Block, read::EbmlReader, Master, MatroskaTag};
use log::debug;
use std::{fs::File, io::BufReader, path::PathBuf};

pub fn extract_track(
    path_base: PathBuf,
    track_info: LocalTrack,
) -> anyhow::Result<Vec<(u64, u64, Vec<u8>)>> {
    let source_path = path_base.join(track_info.path);
    let file = File::open(&source_path)?;
    let mut reader = EbmlReader::new(BufReader::new(file));
    let index = get_seek_index(&source_path)?;
    let index = index
        .get(&(track_info.track as u64))
        .ok_or(anyhow!("track missing"))?;

    let mut out = Vec::new();
    for b in &index.blocks {
        reader.seek(b.source_off, MatroskaTag::BlockGroup(Master::Start))?;
        let (duration, block) = read_group(&mut reader)?;
        assert_eq!(
            track_info.track, block.track as usize,
            "seek index is wrong"
        );
        out.push((b.pts, duration, block.data))
    }
    Ok(out)
}

pub fn read_group(segment: &mut EbmlReader) -> anyhow::Result<(u64, Block)> {
    let (mut dur, mut block) = (None, None);
    for _ in 0..10 {
        let (_, item) = segment.next().ok_or(anyhow!("eof"))??;
        match item {
            MatroskaTag::Void(_) => (),
            MatroskaTag::Crc32(_) => (),
            MatroskaTag::Cluster(_) => bail!("unexpected cluster"),
            MatroskaTag::Timestamp(_) => (),
            MatroskaTag::SimpleBlock(block) => {
                return Ok((1000, block)); // HDMV/PGS does not use duration?!
            }
            MatroskaTag::BlockGroup(Master::Start) => (),
            MatroskaTag::BlockGroup(Master::End) => return Ok((dur.unwrap(), block.unwrap())),
            MatroskaTag::BlockDuration(duration) => dur = Some(duration),
            MatroskaTag::Block(blk) => block = Some(blk),
            MatroskaTag::Cues(_) => bail!("reached cues, this is the end"),
            MatroskaTag::Segment(Master::End) => bail!("extractor reached segment end"),
            _ => debug!("(rs) tag ignored: {item:?}"),
        }
    }
    bail!(".")
}