aboutsummaryrefslogtreecommitdiff
path: root/stream/src/webvtt.rs
blob: 316e224f763bd0d1a7e056221ddc83d7fea21899 (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
/*
    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>
*/
use anyhow::{anyhow, Context, Result};
use jellybase::{cache::async_cache_memory, CONF};
use jellycommon::{stream::StreamSpec, LocalTrack, Node};
use jellyremuxer::extract::extract_track;
use jellytranscoder::subtitles::{parse_subtitles, write_webvtt};
use tokio::io::{AsyncWriteExt, DuplexStream};

pub async fn vtt_stream(
    json: bool,
    node: Node,
    local_tracks: Vec<LocalTrack>,
    spec: StreamSpec,
    mut b: DuplexStream,
) -> Result<()> {
    // TODO cache

    // TODO should use fragments too? big films take too long...

    let tracki = *spec.track.first().ok_or(anyhow!("no track selected"))?;
    let local_track = local_tracks.first().ok_or(anyhow!("no tracks"))?.clone();
    let track = &node.public.media.unwrap().tracks[tracki];
    let cp = local_track.codec_private.clone();

    let subtitles = async_cache_memory(
        &[
            "vtt",
            &format!(
                "{} {}",
                local_track.path.to_str().unwrap(),
                local_track.track
            ),
        ],
        move || async move {
            let blocks = tokio::task::spawn_blocking(move || {
                extract_track(CONF.media_path.clone(), local_track)
            })
            .await??;
            let subtitles = parse_subtitles(&track.codec, cp, blocks)?;
            Ok(subtitles)
        },
    )
    .await?;

    let output = if json {
        serde_json::to_string(subtitles.as_ref())?
    } else {
        write_webvtt(
            node.public.title.clone().unwrap_or_default(),
            subtitles.as_ref(),
        )
        .context("writing webvtt")?
    };
    tokio::task::spawn(async move {
        let _ = b.write_all(output.as_bytes()).await;
    });
    Ok(())
}