aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/stream.rs
blob: 749077c7010ab3b38239ae093fb9b9d59fc14519 (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
/*
    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) 2023 metamuffin <metamuffin.org>
*/
use super::ui::{account::session::Session, error::MyError};
use crate::library::Library;
use anyhow::{anyhow, Context, Result};
use jellyremuxer::RemuxerContext;
use log::{debug, info, warn};
use rocket::{
    get,
    http::{ContentType, Header, Status},
    request::{self, FromRequest},
    response::{self, Responder},
    Request, Response, State,
};
use std::{
    ops::{Deref, Range},
    path::{Path, PathBuf},
};
use tokio::io::{duplex, DuplexStream};
use tokio_util::io::SyncIoBridge;

pub fn stream_uri(path: &Path, tracks: &[u64], webm: bool) -> String {
    format!(
        "/stream/{}?tracks={}&webm={}",
        path.to_str().unwrap(),
        tracks
            .iter()
            .map(|v| format!("{v}"))
            .collect::<Vec<_>>()
            .join(","),
        if webm { "1" } else { "0" }
    )
}

#[get("/stream/<path..>?<tracks>&<webm>")]
pub fn r_stream(
    _sess: Session,
    path: PathBuf,
    webm: Option<bool>,
    tracks: String,
    remuxer: &State<RemuxerContext>,
    library: &State<Library>,
    range: Option<RequestRange>,
) -> Result<StreamResponse, MyError> {
    info!(
        "stream request (range={})",
        range
            .as_ref()
            .map(|r| r.to_cr_hv())
            .unwrap_or(format!("none"))
    );
    let (a, b) = duplex(1024);
    let path = path.to_str().unwrap().to_string();
    let item = library
        .nested(&path)
        .context("retrieving library node")?
        .get_item()?;
    let remuxer = remuxer.deref().clone();
    let tracks = tracks
        .split(',')
        .map(|e| e.parse().map_err(|_| anyhow!("invalid number")))
        .collect::<Result<Vec<_>, _>>()?;

    let b = SyncIoBridge::new(b);

    let urange = match &range {
        Some(r) => {
            // TODO this can crash
            let r = &r.0[0];
            r.start.unwrap_or(0)..r.end.unwrap_or(isize::MAX as usize)
        }
        None => 0..(isize::MAX as usize),
    };

    tokio::task::spawn_blocking(move || {
        if let Err(e) = remuxer.generate_into(
            b,
            urange,
            item.fs_path.parent().unwrap().to_path_buf(),
            item.info.clone(),
            tracks,
            webm.unwrap_or(false),
        ) {
            warn!("stream stopped: {e}")
        }
    });
    debug!("starting stream");
    Ok(StreamResponse { stream: a, range })
}

pub struct StreamResponse {
    stream: DuplexStream,
    range: Option<RequestRange>,
}

#[rocket::async_trait]
impl<'r> Responder<'r, 'static> for StreamResponse {
    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
        let mut b = Response::build();
        if let Some(range) = self.range {
            b.status(Status::PartialContent);
            b.header(Header::new("content-range", range.to_cr_hv()));
        }
        b.header(Header::new("accept-ranges", "bytes"))
            .header(ContentType::WEBM)
            .streamed_body(self.stream)
            .ok()
    }
}

#[derive(Debug)]
pub struct RequestRange(Vec<Range<Option<usize>>>);

impl RequestRange {
    pub fn to_cr_hv(&self) -> String {
        assert_eq!(self.0.len(), 1);
        format!(
            "bytes {}-{}/*",
            self.0[0]
                .start
                .map(|e| format!("{e}"))
                .unwrap_or(String::new()),
            self.0[0]
                .end
                .map(|e| format!("{e}"))
                .unwrap_or(String::new())
        )
    }
    pub fn from_hv(s: &str) -> Result<Self> {
        Ok(Self(
            s.strip_prefix("bytes=")
                .ok_or(anyhow!("prefix expected"))?
                .split(',')
                .map(|s| {
                    let (l, r) = s
                        .split_once('-')
                        .ok_or(anyhow!("range delimeter missing"))?;
                    let km = |s: &str| {
                        if s.is_empty() {
                            Ok::<_, anyhow::Error>(None)
                        } else {
                            Ok(Some(s.parse()?))
                        }
                    };
                    Ok(km(l)?..km(r)?)
                })
                .collect::<Result<Vec<_>>>()?,
        ))
    }
}

#[rocket::async_trait]
impl<'r> FromRequest<'r> for RequestRange {
    type Error = anyhow::Error;

    async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
        match req.headers().get("range").next() {
            Some(v) => match Self::from_hv(v) {
                Ok(v) => rocket::outcome::Outcome::Success(v),
                Err(e) => rocket::outcome::Outcome::Failure((Status::BadRequest, e)),
            },
            None => rocket::outcome::Outcome::Forward(()),
        }
    }
}