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

use anyhow::{anyhow, bail, Context, Result};
use hls::{hls_master_stream, hls_variant_stream};
use jellybase::{permission::PermissionSetExt, CONF};
use jellycommon::{
    stream::{StreamFormat, StreamSpec},
    user::{PermissionSet, UserPermission},
    LocalTrack, Node, TrackSource,
};
use jhls::jhls_index;
use segment::segment_stream;
use std::{io::SeekFrom, ops::Range};
use tokio::{
    fs::File,
    io::{duplex, AsyncReadExt, AsyncSeekExt, AsyncWriteExt, DuplexStream},
};
use tokio_util::io::SyncIoBridge;
use webvtt::webvtt_stream;

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

#[rustfmt::skip]
pub fn stream_head(spec: &StreamSpec) -> StreamHead {
    let webm_or_mkv = if spec.webm.unwrap_or(false)  { "video/webm" } else { "video/x-matroska" }; 
    match spec.format {
        StreamFormat::Original => StreamHead { content_type: "video/x-matroska", range_supported: true },
        StreamFormat::Matroska => StreamHead { content_type: webm_or_mkv, range_supported: true },
        StreamFormat::HlsMaster | StreamFormat::HlsVariant => StreamHead { content_type: "application/vnd.apple.mpegurl", range_supported: false },
        StreamFormat::JhlsIndex => StreamHead { content_type: "application/jellything-seekindex+json", range_supported: false },
        StreamFormat::Webvtt => StreamHead { content_type: "text/vtt", range_supported: false },
        StreamFormat::Snippet => StreamHead { content_type: webm_or_mkv, range_supported: false },
    }
}

pub async fn stream(
    node: Node,
    spec: StreamSpec,
    range: Range<usize>,
    perms: &PermissionSet,
) -> Result<DuplexStream> {
    perms.assert(&UserPermission::StreamFormat(spec.format))?;

    let (a, b) = duplex(4096);

    // TODO remux of mixed remote and local tracks?!
    let track_sources = node
        .private
        .source
        .to_owned()
        .ok_or(anyhow!("node has no media"))?;

    let local_tracks = spec
        .tracks
        .iter()
        .map(|i| {
            anyhow::Ok(
                match track_sources
                    .get(*i)
                    .ok_or(anyhow!("track does not exist"))?
                {
                    TrackSource::Local(t) => t.to_owned(),
                    TrackSource::Remote(_) => bail!("track is not local"),
                },
            )
        })
        .collect::<anyhow::Result<Vec<_>>>()?
        .into_iter()
        .collect::<Vec<_>>();

    match spec.format {
        StreamFormat::Original => original_stream(local_tracks, spec, range, b).await?,
        StreamFormat::Matroska => remux_stream(node, local_tracks, spec, range, b).await?,
        StreamFormat::HlsMaster => hls_master_stream(node, local_tracks, spec, b).await?,
        StreamFormat::HlsVariant => hls_variant_stream(node, local_tracks, spec, b).await?,
        StreamFormat::JhlsIndex => jhls_index(node, &local_tracks, spec, b, perms).await?,
        StreamFormat::Snippet => segment_stream(node, local_tracks, spec, b, perms).await?,
        StreamFormat::Webvtt => webvtt_stream(node, local_tracks, spec, b).await?,
    }

    Ok(a)
}

async fn remux_stream(
    node: 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.public,
            local_tracks,
            spec.tracks,
            spec.webm.unwrap_or(false),
        )
    });

    Ok(())
}

async fn original_stream(
    local_tracks: Vec<LocalTrack>,
    spec: StreamSpec,
    range: Range<usize>,
    b: DuplexStream,
) -> Result<()> {
    if spec.tracks.len() != 1 {
        bail!("invalid amout of source \"tracks\". original only allows for exactly one.")
    }

    let source = local_tracks[spec.tracks[0]].clone();
    let mut file = File::open(CONF.media_path.join(source.path))
        .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;
    }
}