summary refs log tree commit diff
path: root/src/subtitles/mod.rs
blob: a545d52fe571049b591a0b1d8e0cc9fffbda9684 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
pub mod extraction;
pub mod state;

use std::collections::BTreeMap;

use relm4::SharedState;

pub type StreamIndex = usize;

#[derive(Debug, Clone)]
pub struct MetadataCollection {
    pub audio: BTreeMap<StreamIndex, TrackMetadata>,
    pub subtitles: BTreeMap<StreamIndex, TrackMetadata>,
}

#[derive(Debug, Clone)]
pub struct TrackMetadata {
    pub language: Option<isolang::Language>,
    pub title: Option<String>,
}

#[derive(Debug, Clone)]
pub struct SubtitleCue {
    pub text: String,
    pub start_time: gst::ClockTime,
    pub end_time: gst::ClockTime,
}

#[derive(Debug, Clone)]
pub struct SubtitleTrack {
    pub metadata: TrackMetadata,
    // SoA of cue text, start timestamp, end timestamp
    pub texts: Vec<String>,
    pub start_times: Vec<gst::ClockTime>,
    pub end_times: Vec<gst::ClockTime>,
}

pub static SUBTITLE_TRACKS: SharedState<BTreeMap<StreamIndex, SubtitleTrack>> = SharedState::new();

impl TrackMetadata {
    pub fn from_ffmpeg_stream(stream: &ffmpeg::Stream) -> Self {
        let language_code = stream.metadata().get("language").map(|s| s.to_string());
        let title = stream.metadata().get("title").map(|s| s.to_string());

        Self {
            language: language_code.and_then(|code| isolang::Language::from_639_2b(&code)),
            title,
        }
    }
}

impl SubtitleTrack {
    pub fn new(metadata: TrackMetadata) -> Self {
        Self {
            metadata,
            texts: Vec::new(),
            start_times: Vec::new(),
            end_times: Vec::new(),
        }
    }

    pub fn push_cue(&mut self, cue: SubtitleCue) {
        let SubtitleCue {
            text,
            start_time,
            end_time,
        } = cue;

        self.texts.push(text);
        self.start_times.push(start_time);
        self.end_times.push(end_time);
    }

    pub fn iter_cloned_cues(&self) -> impl Iterator<Item = SubtitleCue> {
        self.texts
            .iter()
            .cloned()
            .zip(self.start_times.iter().cloned())
            .zip(self.end_times.iter().cloned())
            .map(|((text, start_time), end_time)| SubtitleCue {
                text,
                start_time,
                end_time,
            })
    }
}