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
|
/*
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::error::MyError;
use crate::library::Library;
use anyhow::{anyhow, Context};
use jellyremuxer::RemuxerContext;
use log::debug;
use log::warn;
use rocket::http::Header;
use rocket::response;
use rocket::response::Responder;
use rocket::Request;
use rocket::Response;
use rocket::{get, http::ContentType, response::stream::ReaderStream, State};
use std::ops::Deref;
use std::path::PathBuf;
use tokio::io::{duplex, DuplexStream};
use tokio_util::io::SyncIoBridge;
pub fn stream_uri(path: &PathBuf, tracks: &Vec<u64>, webm: bool) -> String {
format!(
"/stream/{}?tracks={}&webm={}",
path.to_str().unwrap().to_string(),
tracks
.iter()
.map(|v| format!("{v}"))
.collect::<Vec<_>>()
.join(","),
if webm { "1" } else { "0" }
)
}
#[get("/stream/<path..>?<tracks>&<webm>")]
pub fn r_stream(
path: PathBuf,
webm: Option<bool>,
tracks: String,
remuxer: &State<RemuxerContext>,
library: &State<Library>,
) -> Result<(ContentType, ReaderStream![DuplexStream]), MyError> {
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")))
.into_iter()
.collect::<Result<Vec<_>, _>>()?;
let b = SyncIoBridge::new(b);
tokio::task::spawn_blocking(move || {
if let Err(e) = remuxer.generate_into(
b,
0,
item.fs_path.parent().unwrap().to_path_buf(),
item.info.clone(),
tracks,
webm.unwrap_or(false),
) {
warn!("stream stopped: {e}")
}
});
debug!("starting stream");
Ok((ContentType::WEBM, ReaderStream::one(a)))
}
pub struct StreamResponse {
stream: DuplexStream,
}
#[rocket::async_trait]
impl<'r> Responder<'r, 'static> for StreamResponse {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
Response::build()
.header(Header::new("accept-ranges", "bytes"))
.header(ContentType::WEBM)
.streamed_body(self.stream)
.ok()
}
}
|