aboutsummaryrefslogtreecommitdiff
path: root/common/src/stream.rs
blob: 81dd2980ad3fc96b943a0f13b3eb3046868f1d83 (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
/*
    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) 2025 metamuffin <metamuffin.org>
*/
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fmt::Display, str::FromStr};

pub type SegmentNum = usize;
pub type TrackNum = usize;
pub type FormatNum = usize;
pub type IndexNum = usize;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum StreamSpec {
    Whep {
        track: TrackNum,
        seek: u64,
    },
    WhepControl {
        token: String,
    },
    Remux {
        tracks: Vec<usize>,
        container: StreamContainer,
    },
    Original {
        track: TrackNum,
    },
    HlsSuperMultiVariant {
        container: StreamContainer,
    },
    HlsMultiVariant {
        segment: SegmentNum,
        container: StreamContainer,
    },
    HlsVariant {
        segment: SegmentNum,
        track: TrackNum,
        container: StreamContainer,
        format: FormatNum,
    },
    Info {
        segment: Option<u64>,
    },
    FragmentIndex {
        segment: SegmentNum,
        track: TrackNum,
    },
    Fragment {
        segment: SegmentNum,
        track: TrackNum,
        index: IndexNum,
        container: StreamContainer,
        format: FormatNum,
    },
    // Track {
    //     segment: SegmentNum,
    //     track: TrackNum,
    //     container: StreamContainer,
    //     foramt: FormatNum,
    // },
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StreamInfo {
    pub name: Option<String>,
    pub segments: Vec<StreamSegmentInfo>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StreamSegmentInfo {
    pub name: Option<String>,
    pub duration: f64,
    pub tracks: Vec<StreamTrackInfo>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StreamTrackInfo {
    pub name: Option<String>,
    pub kind: TrackKind,
    pub formats: Vec<StreamFormatInfo>,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TrackKind {
    Video,
    Audio,
    Subtitle,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct StreamFormatInfo {
    pub codec: String,
    pub bitrate: f64,
    pub remux: bool,
    pub containers: Vec<StreamContainer>,

    pub width: Option<u64>,
    pub height: Option<u64>,
    pub samplerate: Option<f64>,
    pub channels: Option<usize>,
    pub bit_depth: Option<u8>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum StreamContainer {
    WebM,
    Matroska,
    WebVTT,
    MPEG4,
    JVTT,
}

impl StreamSpec {
    pub fn to_query(&self) -> String {
        match self {
            StreamSpec::Whep { track, seek } => format!("?whep&track={track}&seek={seek}"),
            StreamSpec::WhepControl { token } => format!("?whepcontrol&token={token}"),
            StreamSpec::Remux { tracks, container } => {
                format!(
                    "?remux&tracks={}&container={container}",
                    tracks
                        .iter()
                        .map(|t| t.to_string())
                        .collect::<Vec<String>>()
                        .join(",")
                )
            }
            StreamSpec::Original { track } => format!("?original&track={track}"),
            StreamSpec::HlsSuperMultiVariant { container } => {
                format!("?hlssupermultivariant&container={container}")
            }
            StreamSpec::HlsMultiVariant { segment, container } => {
                format!("?hlsmultivariant&segment={segment}&container={container}")
            }
            StreamSpec::HlsVariant {
                segment,
                track,
                container,
                format,
            } => format!(
                "?hlsvariant&segment={segment}&track={track}&container={container}&format={format}"
            ),
            StreamSpec::Info {
                segment: Some(segment),
            } => format!("?info&segment={segment}"),
            StreamSpec::Info { segment: None } => "?info".to_string(),
            StreamSpec::FragmentIndex { segment, track } => {
                format!("?fragmentindex&segment={segment}&track={track}")
            }
            StreamSpec::Fragment {
                segment,
                track,
                index,
                container,
                format,
            } => format!("?fragment&segment={segment}&track={track}&index={index}&container={container}&format={format}"),
        }
    }
    pub fn from_query_kv(query: &BTreeMap<String, String>) -> Result<Self, &'static str> {
        let get_num = |k: &'static str| {
            query
                .get(k)
                .ok_or(k)
                .and_then(|a| a.parse().map_err(|_| "invalid number"))
        };
        let get_container = || {
            query
                .get("container")
                .ok_or("container")
                .and_then(|s| s.parse().map_err(|()| "unknown container"))
        };
        if query.contains_key("info") {
            Ok(Self::Info {
                segment: get_num("segment").ok(),
            })
        } else if query.contains_key("hlssupermultivariant") {
            Ok(Self::HlsSuperMultiVariant {
                container: get_container().ok().unwrap_or(StreamContainer::Matroska),
            })
        } else if query.contains_key("hlsmultivariant") {
            Ok(Self::HlsMultiVariant {
                segment: get_num("segment")? as SegmentNum,
                container: get_container()?,
            })
        } else if query.contains_key("hlsvariant") {
            Ok(Self::HlsVariant {
                segment: get_num("segment")? as SegmentNum,
                track: get_num("track")? as TrackNum,
                format: get_num("format")? as FormatNum,
                container: get_container()?,
            })
        } else if query.contains_key("fragment") {
            Ok(Self::Fragment {
                segment: get_num("segment")? as SegmentNum,
                track: get_num("track")? as TrackNum,
                format: get_num("format")? as FormatNum,
                index: get_num("index")? as IndexNum,
                container: get_container()?,
            })
        } else if query.contains_key("fragmentindex") {
            Ok(Self::FragmentIndex {
                segment: get_num("segment")? as SegmentNum,
                track: get_num("track")? as TrackNum,
            })
        } else {
            Err("invalid stream spec")
        }
    }
}

impl Display for StreamContainer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            StreamContainer::WebM => "webm",
            StreamContainer::Matroska => "matroska",
            StreamContainer::WebVTT => "webvtt",
            StreamContainer::JVTT => "jvtt",
            StreamContainer::MPEG4 => "mpeg4",
        })
    }
}
impl FromStr for StreamContainer {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "webm" => StreamContainer::WebM,
            "matroska" => StreamContainer::Matroska,
            "webvtt" => StreamContainer::WebVTT,
            "jvtt" => StreamContainer::JVTT,
            "mpeg4" => StreamContainer::MPEG4,
            _ => return Err(()),
        })
    }
}