aboutsummaryrefslogtreecommitdiff
path: root/stream/src/lib.rs
blob: d09759f71a2e77866f84cbee653de0e81aa5568f (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
/*
    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>
*/
#![feature(iterator_try_collect)]
pub mod fragment;
pub mod hls;
pub mod jhls;
pub mod webvtt;

use anyhow::{anyhow, Context, Result};
use jellybase::common::{
    stream::{
        StreamContainer, StreamFormatInfo, StreamInfo, StreamSegmentInfo, StreamSpec,
        StreamTrackInfo, TrackKind,
    },
    LocalTrack, Node,
};
use jellyremuxer::metadata::{matroska_metadata, MatroskaMetadata};
use std::{collections::BTreeSet, io::SeekFrom, ops::Range, path::PathBuf, sync::Arc};
use tokio::{
    fs::File,
    io::{duplex, AsyncReadExt, AsyncSeekExt, AsyncWriteExt, DuplexStream},
    task::spawn_blocking,
};
use tokio_util::io::SyncIoBridge;

#[derive(Debug)]
pub struct SMediaInfo {
    pub info: Arc<Node>,
    pub files: BTreeSet<PathBuf>,
}

pub struct StreamHead {
    pub content_type: &'static str,
    pub range_supported: bool,
}

pub fn stream_head(spec: &StreamSpec) -> StreamHead {
    let cons = |ct: &'static str, rs: bool| StreamHead {
        content_type: ct,
        range_supported: rs,
    };
    let container_ct = |x: StreamContainer| match x {
        StreamContainer::WebM => "video/webm",
        StreamContainer::Matroska => "video/x-matroska",
        StreamContainer::WebVTT => "text/vtt",
        StreamContainer::JVTT => "application/jellything-vtt+json",
    };
    match spec {
        StreamSpec::Whep { .. } => cons("application/x-todo", false),
        StreamSpec::WhepControl { .. } => cons("application/x-todo", false),
        StreamSpec::Remux { container, .. } => cons(container_ct(*container), true),
        StreamSpec::Original { .. } => cons("video/x-matroska", true),
        StreamSpec::HlsSuperMultiVariant { .. } => cons("application/vnd.apple.mpegurl", false),
        StreamSpec::HlsMultiVariant { .. } => cons("application/vnd.apple.mpegurl", false),
        StreamSpec::HlsVariant { .. } => cons("application/vnd.apple.mpegurl", false),
        StreamSpec::Info { .. } => cons("application/jellything-stream-info+json", false),
        StreamSpec::FragmentIndex { .. } => cons("application/jellything-frag-index+json", false),
        StreamSpec::Fragment { container, .. } => cons(container_ct(*container), false),
    }
}

pub async fn stream(
    info: Arc<SMediaInfo>,
    spec: StreamSpec,
    range: Range<usize>,
) -> Result<DuplexStream> {
    let (a, b) = duplex(4096);

    match spec {
        StreamSpec::Whep { track, seek } => todo!(),
        StreamSpec::WhepControl { token } => todo!(),
        StreamSpec::Remux { tracks, container } => todo!(),
        StreamSpec::Original { track } => original_stream(info, track, range, b).await?,
        StreamSpec::HlsSuperMultiVariant { container } => todo!(),
        StreamSpec::HlsMultiVariant { segment, container } => todo!(),
        StreamSpec::HlsVariant {
            segment,
            track,
            container,
            format,
        } => todo!(),
        StreamSpec::Info { segment } => write_stream_info(info, b).await?,
        StreamSpec::FragmentIndex { segment, track } => todo!(),
        StreamSpec::Fragment {
            segment,
            track,
            index,
            container,
            format,
        } => todo!(),
    }

    Ok(a)
}

async fn async_matroska_metadata(path: PathBuf) -> Result<Arc<MatroskaMetadata>> {
    Ok(spawn_blocking(move || matroska_metadata(&path)).await??)
}

pub(crate) struct InternalStreamInfo {
    pub paths: Vec<PathBuf>,
    pub metadata: Vec<Arc<MatroskaMetadata>>,
    pub track_to_file: Vec<usize>,
}

async fn stream_info(info: Arc<SMediaInfo>) -> Result<(InternalStreamInfo, StreamInfo)> {
    let mut metadata = Vec::new();
    let mut paths = Vec::new();
    for path in &info.files {
        metadata.push(async_matroska_metadata(path.clone()).await?);
        paths.push(path.clone());
    }

    let mut tracks = Vec::new();
    let mut track_to_file = Vec::new();

    for (i, m) in metadata.iter().enumerate() {
        if let Some(t) = &m.tracks {
            for t in &t.entries {
                let mut formats = Vec::new();
                formats.push(StreamFormatInfo {
                    codec: t.codec_id.to_string(),
                    remux: true,
                    byterate: 10., // TODO
                    containers: [StreamContainer::Matroska].to_vec(),
                    bit_depth: t.audio.as_ref().and_then(|a| a.bit_depth.map(|e| e as u8)),
                    samplerate: t.audio.as_ref().map(|a| a.sampling_frequency),
                    channels: t.audio.as_ref().map(|a| a.channels as usize),
                    pixel_count: t.video.as_ref().map(|v| v.pixel_width * v.pixel_height),
                    ..Default::default()
                });
                tracks.push(StreamTrackInfo {
                    name: None,
                    kind: match t.track_type {
                        1 => TrackKind::Video,
                        2 => TrackKind::Audio,
                        17 => TrackKind::Subtitle,
                        _ => todo!(),
                    },
                    formats,
                });
                track_to_file.push(i);
            }
        }
    }

    let segment = StreamSegmentInfo {
        name: None,
        duration: 0,
        tracks,
    };
    Ok((
        InternalStreamInfo {
            metadata,
            paths,
            track_to_file,
        },
        StreamInfo {
            name: info.info.title.clone(),
            segments: vec![segment],
        },
    ))
}

async fn write_stream_info(info: Arc<SMediaInfo>, mut b: DuplexStream) -> Result<()> {
    let (_, info) = stream_info(info).await?;
    b.write_all(&serde_json::to_vec(&info)?).await?;
    Ok(())
}

async fn remux_stream(
    node: Arc<Node>,
    local_tracks: Vec<LocalTrack>,
    spec: StreamSpec,
    range: Range<usize>,
    b: DuplexStream,
) -> Result<()> {
    let b = SyncIoBridge::new(b);

    // tokio::task::spawn_blocking(move || {
    //     jellyremuxer::remux_stream_into(
    //         b,
    //         range,
    //         CONF.media_path.to_owned(),
    //         &node,
    //         local_tracks,
    //         spec.track,
    //         spec.webm.unwrap_or(false),
    //     )
    // });

    Ok(())
}

async fn original_stream(
    info: Arc<SMediaInfo>,
    track: usize,
    range: Range<usize>,
    b: DuplexStream,
) -> Result<()> {
    let (iinfo, _info) = stream_info(info).await?;

    let file_index = *iinfo
        .track_to_file
        .get(track)
        .ok_or(anyhow!("unknown track"))?;
    let mut file = File::open(&iinfo.paths[file_index])
        .await
        .context("opening source")?;
    file.seek(SeekFrom::Start(range.start as u64))
        .await
        .context("seek source")?;

    tokio::task::spawn(copy_stream(file, b, range.end - range.start));

    Ok(())
}

async fn copy_stream(mut inp: File, mut out: DuplexStream, mut amount: usize) -> Result<()> {
    let mut buf = [0u8; 4096];
    loop {
        let size = inp.read(&mut buf[..amount.min(4096)]).await?;
        if size == 0 {
            break Ok(());
        }
        out.write_all(&buf[..size]).await?;
        amount -= size;
    }
}