aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/stream.rs
blob: 0e1fccb9234ab4e347f31f41680ac5a1bb647d63 (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
use crate::library::Library;

use super::ui::error::MyError;
use anyhow::{anyhow, Context};
use jellyremuxer::RemuxerContext;
use log::debug;
use log::warn;
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>) -> String {
    format!(
        "/stream/{}?tracks={}",
        path.to_str().unwrap().to_string(),
        tracks
            .iter()
            .map(|v| format!("{v}"))
            .collect::<Vec<_>>()
            .join(",")
    )
}

#[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)))
}