diff --git a/transcoder/src/state.rs b/transcoder/src/state.rs index a91091fc..e43e6e96 100644 --- a/transcoder/src/state.rs +++ b/transcoder/src/state.rs @@ -5,6 +5,7 @@ use crate::utils::Signalable; use std::collections::HashMap; use std::path::PathBuf; use std::sync::RwLock; +use std::time::{Duration, SystemTime}; pub struct Transcoder { running: RwLock>, @@ -19,6 +20,18 @@ impl Transcoder { } } + fn clean_old_transcode(&self) { + for info in self.running.write().unwrap().values_mut() { + if SystemTime::now() + .duration_since(*info.last_used.read().unwrap()) + .is_ok_and(|d| d > Duration::new(4 * 60 * 60, 0)) + { + _ = info.job.interrupt(); + _ = std::fs::remove_dir_all(get_cache_path_from_uuid(&info.uuid)); + } + } + } + pub async fn build_master(&self, resource: String, slug: String) -> Option { let mut master = String::from("#EXTM3U\n"); let path = get_path(resource, slug).await.ok()?; @@ -123,6 +136,8 @@ impl Transcoder { } } + self.clean_old_transcode(); + let info = transcode_video(path, quality, start_time).await?; let mut path = get_cache_path(&info); path.push("stream.m3u8"); @@ -141,6 +156,10 @@ impl Transcoder { let hashmap = self.running.read().unwrap(); let info = hashmap.get(&client_id).ok_or(SegmentError::NoTranscode)?; + if let Ok(mut last) = info.last_used.try_write() { + *last = SystemTime::now(); + } + // If the segment is in the playlist file, it is available so we don't need to check that. let mut path = get_cache_path(&info); path.push(format!("segments-{0:02}.ts", chunk)); diff --git a/transcoder/src/transcode.rs b/transcoder/src/transcode.rs index b1949d22..6324799d 100644 --- a/transcoder/src/transcode.rs +++ b/transcoder/src/transcode.rs @@ -8,6 +8,8 @@ use std::path::PathBuf; use std::process::Stdio; use std::slice::Iter; use std::str::FromStr; +use std::sync::RwLock; +use std::time::SystemTime; use tokio::io::{AsyncBufReadExt, BufReader}; use tokio::process::{Child, Command}; use tokio::sync::watch; @@ -229,6 +231,7 @@ pub async fn transcode_video( show: (path, quality), job: child, uuid, + last_used: RwLock::new(SystemTime::now()) }) } @@ -323,4 +326,5 @@ pub struct TranscodeInfo { pub show: (String, Quality), pub job: Child, pub uuid: String, + pub last_used: RwLock, }