aboutsummaryrefslogtreecommitdiff
path: root/transcoder/src/subtitles.rs
blob: 27e01ccea5a272f22edb237df64ffcf7722d4822 (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
use anyhow::anyhow;
use std::fmt::Write;

pub fn webvtt_from_ass_blocks(
    title: String,
    _codec_private: Vec<u8>,
    blocks: Vec<(u64, u64, Vec<u8>)>,
) -> anyhow::Result<String> {
    let mut out = String::new();

    writeln!(out, "WEBVTT - {title}")?; // TODO ensure title does not contain "-->"
    writeln!(out)?;

    for (pts, dur, block) in blocks {
        let block = String::from_utf8(block)?;
        let text = convert_block(&block).ok_or(anyhow!("bad ass xD"))?;
        writeln!(out, "{} --> {}", format_time(pts), format_time(pts + dur))?;
        writeln!(out, "- {text}")?;
        writeln!(out)?;
    }

    Ok(out)
}

fn format_time(t: u64) -> String {
    let t = t as f64 / 1_000_000.;

    // let mmm = (t.fract() * 1000.).floor();
    // let mmm = ((t * 60.).fract() * 60.).floor();
    // let mmm = ((t / 60).fract() * 60.).floor();

    // format!("{hh:4}:{mm:02}:{ss:02}.{mmm:03}")
    format!("{t}")
}

fn convert_block(s: &str) -> Option<&str> {
    // ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text
    let (_read_order, s) = s.split_once(',')?;
    let (_layer, s) = s.split_once(',')?;
    let (_style, s) = s.split_once(',')?;
    let (_name, s) = s.split_once(',')?;
    let (_marginl, s) = s.split_once(',')?;
    let (_marginr, s) = s.split_once(',')?;
    let (_marginv, s) = s.split_once(',')?;
    let (_effect, text) = s.split_once(',')?;

    Some(text)
}