Add rolling replay media pipeline
This commit is contained in:
1 parent
0338342051
commit
af3e6c28e5
11 files changed
+3182
-130
No files matched your search
+235
-30
@@ -31,7 +31,10 @@ pub struct CaptureConfig {
|
||||
pub fps: u32,
|
||||
pub bitrate_kbps: u32,
|
||||
pub encoder: EncoderPreference,
|
||||
pub system_audio_enabled: bool,
|
||||
pub mic_enabled: bool,
|
||||
pub system_audio_device: Option<String>,
|
||||
pub mic_device: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -126,42 +129,125 @@ impl FfmpegRecordingPlan {
|
||||
output: impl Into<PathBuf>,
|
||||
config: &CaptureConfig,
|
||||
) -> Self {
|
||||
let preset = match config.encoder {
|
||||
EncoderPreference::HardwareH264 => "h264_mf",
|
||||
EncoderPreference::SoftwareH264 => "libx264",
|
||||
};
|
||||
let output = output.into();
|
||||
let size = format!("{}x{}", config.width, config.height);
|
||||
let fps = config.fps.to_string();
|
||||
let bitrate = format!("{}k", config.bitrate_kbps);
|
||||
|
||||
let mut args = base_desktop_input_args(config);
|
||||
args.extend([
|
||||
"-movflags".to_string(),
|
||||
"+faststart".to_string(),
|
||||
output.display().to_string(),
|
||||
]);
|
||||
|
||||
Self {
|
||||
executable: executable.into(),
|
||||
args: vec![
|
||||
"-y".to_string(),
|
||||
"-hide_banner".to_string(),
|
||||
"-loglevel".to_string(),
|
||||
"error".to_string(),
|
||||
"-f".to_string(),
|
||||
"gdigrab".to_string(),
|
||||
"-framerate".to_string(),
|
||||
fps,
|
||||
"-video_size".to_string(),
|
||||
size,
|
||||
"-i".to_string(),
|
||||
"desktop".to_string(),
|
||||
"-c:v".to_string(),
|
||||
preset.to_string(),
|
||||
"-b:v".to_string(),
|
||||
bitrate,
|
||||
"-pix_fmt".to_string(),
|
||||
"yuv420p".to_string(),
|
||||
"-movflags".to_string(),
|
||||
"+faststart".to_string(),
|
||||
output.display().to_string(),
|
||||
],
|
||||
args,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn for_windows_desktop_segments(
|
||||
executable: impl Into<PathBuf>,
|
||||
output_pattern: impl Into<PathBuf>,
|
||||
config: &CaptureConfig,
|
||||
segment_duration: Duration,
|
||||
) -> Self {
|
||||
let output_pattern = output_pattern.into();
|
||||
let mut args = base_desktop_input_args(config);
|
||||
args.extend([
|
||||
"-f".to_string(),
|
||||
"segment".to_string(),
|
||||
"-segment_time".to_string(),
|
||||
segment_duration.as_secs().max(1).to_string(),
|
||||
"-reset_timestamps".to_string(),
|
||||
"1".to_string(),
|
||||
"-segment_format".to_string(),
|
||||
"mp4".to_string(),
|
||||
output_pattern.display().to_string(),
|
||||
]);
|
||||
|
||||
Self {
|
||||
executable: executable.into(),
|
||||
args,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn base_desktop_input_args(config: &CaptureConfig) -> Vec<String> {
|
||||
let preset = match config.encoder {
|
||||
EncoderPreference::HardwareH264 => "h264_mf",
|
||||
EncoderPreference::SoftwareH264 => "libx264",
|
||||
};
|
||||
let size = format!("{}x{}", config.width, config.height);
|
||||
let fps = config.fps.to_string();
|
||||
let bitrate = format!("{}k", config.bitrate_kbps);
|
||||
let mut args = vec![
|
||||
"-y".to_string(),
|
||||
"-hide_banner".to_string(),
|
||||
"-loglevel".to_string(),
|
||||
"error".to_string(),
|
||||
"-f".to_string(),
|
||||
"gdigrab".to_string(),
|
||||
"-framerate".to_string(),
|
||||
fps,
|
||||
"-video_size".to_string(),
|
||||
size,
|
||||
"-i".to_string(),
|
||||
"desktop".to_string(),
|
||||
];
|
||||
let mut next_input_index = 1;
|
||||
let mut audio_maps = Vec::new();
|
||||
|
||||
if config.system_audio_enabled {
|
||||
args.extend([
|
||||
"-f".to_string(),
|
||||
"wasapi".to_string(),
|
||||
"-i".to_string(),
|
||||
config
|
||||
.system_audio_device
|
||||
.clone()
|
||||
.unwrap_or_else(|| "default".to_string()),
|
||||
]);
|
||||
audio_maps.push(format!("{next_input_index}:a?"));
|
||||
next_input_index += 1;
|
||||
}
|
||||
|
||||
if config.mic_enabled {
|
||||
args.extend([
|
||||
"-f".to_string(),
|
||||
"dshow".to_string(),
|
||||
"-i".to_string(),
|
||||
format!(
|
||||
"audio={}",
|
||||
config
|
||||
.mic_device
|
||||
.clone()
|
||||
.unwrap_or_else(|| "Microphone".to_string())
|
||||
),
|
||||
]);
|
||||
audio_maps.push(format!("{next_input_index}:a?"));
|
||||
}
|
||||
|
||||
args.extend([
|
||||
"-map".to_string(),
|
||||
"0:v:0".to_string(),
|
||||
"-c:v".to_string(),
|
||||
preset.to_string(),
|
||||
"-b:v".to_string(),
|
||||
bitrate,
|
||||
"-pix_fmt".to_string(),
|
||||
"yuv420p".to_string(),
|
||||
]);
|
||||
for audio_map in audio_maps {
|
||||
args.extend(["-map".to_string(), audio_map]);
|
||||
}
|
||||
if config.system_audio_enabled || config.mic_enabled {
|
||||
args.extend([
|
||||
"-c:a".to_string(),
|
||||
"aac".to_string(),
|
||||
"-b:a".to_string(),
|
||||
"160k".to_string(),
|
||||
]);
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -239,6 +325,96 @@ impl Drop for FfmpegCaptureBackend {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FfmpegReplayCaptureBackend {
|
||||
executable: PathBuf,
|
||||
output_pattern: PathBuf,
|
||||
segment_duration: Duration,
|
||||
child: Option<Child>,
|
||||
}
|
||||
|
||||
impl FfmpegReplayCaptureBackend {
|
||||
pub fn new(
|
||||
executable: impl Into<PathBuf>,
|
||||
output_pattern: impl Into<PathBuf>,
|
||||
segment_duration: Duration,
|
||||
) -> Self {
|
||||
Self {
|
||||
executable: executable.into(),
|
||||
output_pattern: output_pattern.into(),
|
||||
segment_duration,
|
||||
child: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn plan(&self, config: &CaptureConfig) -> FfmpegRecordingPlan {
|
||||
FfmpegRecordingPlan::for_windows_desktop_segments(
|
||||
&self.executable,
|
||||
&self.output_pattern,
|
||||
config,
|
||||
self.segment_duration,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl CaptureBackend for FfmpegReplayCaptureBackend {
|
||||
fn name(&self) -> &'static str {
|
||||
"ffmpeg-gdigrab-segments"
|
||||
}
|
||||
|
||||
fn start(&mut self, config: CaptureConfig) -> Result<(), CaptureError> {
|
||||
if self.child.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let plan = self.plan(&config);
|
||||
let child = Command::new(&plan.executable)
|
||||
.args(&plan.args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?;
|
||||
self.child = Some(child);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stop(&mut self) -> Result<(), CaptureError> {
|
||||
stop_ffmpeg_child(&mut self.child)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FfmpegReplayCaptureBackend {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_ffmpeg_child(child: &mut Option<Child>) -> Result<(), CaptureError> {
|
||||
if let Some(mut child) = child.take() {
|
||||
if let Some(stdin) = child.stdin.as_mut() {
|
||||
let _ = stdin.write_all(b"q\n");
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
if child
|
||||
.try_wait()
|
||||
.map_err(|error| CaptureError::DeviceUnavailable(error.to_string()))?
|
||||
.is_some()
|
||||
{
|
||||
break;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -252,7 +428,10 @@ mod tests {
|
||||
fps: 30,
|
||||
bitrate_kbps: 6000,
|
||||
encoder: EncoderPreference::HardwareH264,
|
||||
system_audio_enabled: false,
|
||||
mic_enabled: false,
|
||||
system_audio_device: None,
|
||||
mic_device: None,
|
||||
};
|
||||
|
||||
let plan = FfmpegRecordingPlan::for_windows_desktop("ffmpeg", "out.mp4", &config);
|
||||
@@ -261,4 +440,30 @@ mod tests {
|
||||
assert!(plan.args.contains(&"1280x720".to_string()));
|
||||
assert!(plan.args.contains(&"6000k".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_segment_plan_uses_segment_muxer() {
|
||||
let config = CaptureConfig {
|
||||
source: CaptureSource::Desktop,
|
||||
width: 1280,
|
||||
height: 720,
|
||||
fps: 30,
|
||||
bitrate_kbps: 6000,
|
||||
encoder: EncoderPreference::HardwareH264,
|
||||
system_audio_enabled: false,
|
||||
mic_enabled: false,
|
||||
system_audio_device: None,
|
||||
mic_device: None,
|
||||
};
|
||||
|
||||
let plan = FfmpegRecordingPlan::for_windows_desktop_segments(
|
||||
"ffmpeg",
|
||||
"segment-%05d.mp4",
|
||||
&config,
|
||||
Duration::from_secs(5),
|
||||
);
|
||||
|
||||
assert!(plan.args.contains(&"segment".to_string()));
|
||||
assert!(plan.args.contains(&"segment-%05d.mp4".to_string()));
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
use crate::models::{Clip, ClipSource, GameEventType, UploadProvider};
|
||||
use rusqlite::{params, Connection};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ClipDatabase {
|
||||
connection: Connection,
|
||||
}
|
||||
|
||||
impl ClipDatabase {
|
||||
pub fn open(path: impl AsRef<Path>) -> rusqlite::Result<Self> {
|
||||
let path = path.as_ref();
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?;
|
||||
}
|
||||
let connection = Connection::open(path)?;
|
||||
let database = Self { connection };
|
||||
database.init()?;
|
||||
Ok(database)
|
||||
}
|
||||
|
||||
pub fn init(&self) -> rusqlite::Result<()> {
|
||||
self.connection.execute_batch(
|
||||
"
|
||||
CREATE TABLE IF NOT EXISTS clips (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
session_id TEXT NOT NULL,
|
||||
game_id TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
thumbnail_path TEXT,
|
||||
created_at_ms INTEGER NOT NULL,
|
||||
duration_ms INTEGER NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
event_type TEXT,
|
||||
tags_json TEXT NOT NULL,
|
||||
upload_url TEXT,
|
||||
upload_provider TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS clips_created_at_idx ON clips(created_at_ms DESC);
|
||||
CREATE INDEX IF NOT EXISTS clips_game_id_idx ON clips(game_id);
|
||||
",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn load_clips(&self) -> rusqlite::Result<Vec<Clip>> {
|
||||
let mut statement = self.connection.prepare(
|
||||
"
|
||||
SELECT id, session_id, game_id, path, thumbnail_path, created_at_ms, duration_ms,
|
||||
source, event_type, tags_json, upload_url, upload_provider
|
||||
FROM clips
|
||||
ORDER BY created_at_ms DESC
|
||||
",
|
||||
)?;
|
||||
|
||||
let rows = statement.query_map([], |row| {
|
||||
let tags_json: String = row.get(9)?;
|
||||
let tags = serde_json::from_str::<Vec<String>>(&tags_json).unwrap_or_default();
|
||||
let event_type = row
|
||||
.get::<_, Option<String>>(8)?
|
||||
.map(|value| parse_event_type(&value));
|
||||
let upload_provider = row
|
||||
.get::<_, Option<String>>(11)?
|
||||
.and_then(|value| parse_upload_provider(&value));
|
||||
|
||||
Ok(Clip {
|
||||
id: row.get(0)?,
|
||||
session_id: row.get(1)?,
|
||||
game_id: row.get(2)?,
|
||||
path: PathBuf::from(row.get::<_, String>(3)?),
|
||||
thumbnail_path: row.get::<_, Option<String>>(4)?.map(PathBuf::from),
|
||||
created_at: millis_to_system_time(row.get(5)?),
|
||||
duration: Duration::from_millis(row.get::<_, i64>(6)?.max(0) as u64),
|
||||
source: parse_clip_source(&row.get::<_, String>(7)?),
|
||||
event_type,
|
||||
tags,
|
||||
upload_url: row.get(10)?,
|
||||
upload_provider,
|
||||
})
|
||||
})?;
|
||||
|
||||
rows.collect()
|
||||
}
|
||||
|
||||
pub fn upsert_clip(&self, clip: &Clip) -> rusqlite::Result<()> {
|
||||
let tags_json = serde_json::to_string(&clip.tags).unwrap_or_else(|_| "[]".to_string());
|
||||
self.connection.execute(
|
||||
"
|
||||
INSERT INTO clips (
|
||||
id, session_id, game_id, path, thumbnail_path, created_at_ms, duration_ms,
|
||||
source, event_type, tags_json, upload_url, upload_provider
|
||||
)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
session_id = excluded.session_id,
|
||||
game_id = excluded.game_id,
|
||||
path = excluded.path,
|
||||
thumbnail_path = excluded.thumbnail_path,
|
||||
created_at_ms = excluded.created_at_ms,
|
||||
duration_ms = excluded.duration_ms,
|
||||
source = excluded.source,
|
||||
event_type = excluded.event_type,
|
||||
tags_json = excluded.tags_json,
|
||||
upload_url = excluded.upload_url,
|
||||
upload_provider = excluded.upload_provider
|
||||
",
|
||||
params![
|
||||
clip.id,
|
||||
clip.session_id,
|
||||
clip.game_id,
|
||||
clip.path.display().to_string(),
|
||||
clip.thumbnail_path
|
||||
.as_ref()
|
||||
.map(|path| path.display().to_string()),
|
||||
system_time_to_millis(clip.created_at),
|
||||
clip.duration.as_millis().min(i64::MAX as u128) as i64,
|
||||
clip_source_name(&clip.source),
|
||||
clip.event_type.as_ref().map(ToString::to_string),
|
||||
tags_json,
|
||||
clip.upload_url,
|
||||
clip.upload_provider.as_ref().map(upload_provider_name),
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn delete_clip(&self, clip_id: &str) -> rusqlite::Result<()> {
|
||||
self.connection
|
||||
.execute("DELETE FROM clips WHERE id = ?1", params![clip_id])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_clip_source(value: &str) -> ClipSource {
|
||||
match value {
|
||||
"manual_hotkey" => ClipSource::ManualHotkey,
|
||||
"auto_event" => ClipSource::AutoEvent,
|
||||
"full_session_bookmark" => ClipSource::FullSessionBookmark,
|
||||
_ => ClipSource::Imported,
|
||||
}
|
||||
}
|
||||
|
||||
fn clip_source_name(source: &ClipSource) -> &'static str {
|
||||
match source {
|
||||
ClipSource::ManualHotkey => "manual_hotkey",
|
||||
ClipSource::AutoEvent => "auto_event",
|
||||
ClipSource::FullSessionBookmark => "full_session_bookmark",
|
||||
ClipSource::Imported => "imported",
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_event_type(value: &str) -> GameEventType {
|
||||
match value {
|
||||
"kill" => GameEventType::Kill,
|
||||
"death" => GameEventType::Death,
|
||||
"assist" => GameEventType::Assist,
|
||||
"round_win" => GameEventType::RoundWin,
|
||||
"match_win" => GameEventType::MatchWin,
|
||||
"objective" => GameEventType::Objective,
|
||||
"multi_kill" => GameEventType::MultiKill,
|
||||
"bookmark" => GameEventType::Bookmark,
|
||||
value => GameEventType::Unknown(value.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_upload_provider(value: &str) -> Option<UploadProvider> {
|
||||
match value {
|
||||
"catbox" => Some(UploadProvider::Catbox),
|
||||
"litterbox" => Some(UploadProvider::Litterbox),
|
||||
"lustful" => Some(UploadProvider::Lustful),
|
||||
"custom_http" => Some(UploadProvider::CustomHttp),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn upload_provider_name(provider: &UploadProvider) -> &'static str {
|
||||
match provider {
|
||||
UploadProvider::Catbox => "catbox",
|
||||
UploadProvider::Litterbox => "litterbox",
|
||||
UploadProvider::Lustful => "lustful",
|
||||
UploadProvider::CustomHttp => "custom_http",
|
||||
}
|
||||
}
|
||||
|
||||
fn system_time_to_millis(time: SystemTime) -> i64 {
|
||||
time.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis()
|
||||
.min(i64::MAX as u128) as i64
|
||||
}
|
||||
|
||||
fn millis_to_system_time(millis: i64) -> SystemTime {
|
||||
UNIX_EPOCH + Duration::from_millis(millis.max(0) as u64)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_clip_records() {
|
||||
let db_path = std::env::temp_dir().join(format!(
|
||||
"clipforge-db-{}.sqlite",
|
||||
system_time_to_millis(SystemTime::now())
|
||||
));
|
||||
let database = ClipDatabase::open(&db_path).expect("database");
|
||||
let clip = Clip {
|
||||
id: "clip-1".to_string(),
|
||||
session_id: "session-1".to_string(),
|
||||
game_id: "counter-strike-2".to_string(),
|
||||
path: PathBuf::from("C:/clips/clip-1.mp4"),
|
||||
thumbnail_path: Some(PathBuf::from("C:/clips/clip-1.jpg")),
|
||||
created_at: UNIX_EPOCH + Duration::from_secs(10),
|
||||
duration: Duration::from_secs(60),
|
||||
source: ClipSource::ManualHotkey,
|
||||
event_type: Some(GameEventType::Kill),
|
||||
tags: vec!["clutch".to_string()],
|
||||
upload_url: Some("https://example.test/clip.mp4".to_string()),
|
||||
upload_provider: Some(UploadProvider::CustomHttp),
|
||||
};
|
||||
|
||||
database.upsert_clip(&clip).expect("upsert");
|
||||
let loaded = database.load_clips().expect("load");
|
||||
|
||||
assert_eq!(loaded, vec![clip]);
|
||||
database.delete_clip("clip-1").expect("delete");
|
||||
assert!(database.load_clips().expect("load empty").is_empty());
|
||||
let _ = std::fs::remove_file(db_path);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
pub mod capture;
|
||||
pub mod database;
|
||||
pub mod game_detection;
|
||||
pub mod hotkeys;
|
||||
pub mod integrations;
|
||||
pub mod jobs;
|
||||
pub mod library;
|
||||
pub mod media;
|
||||
pub mod models;
|
||||
pub mod recorder;
|
||||
pub mod settings;
|
||||
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SegmentFile {
|
||||
pub path: PathBuf,
|
||||
pub modified_at: SystemTime,
|
||||
}
|
||||
|
||||
pub fn collect_segments(buffer_dir: &Path) -> io::Result<Vec<SegmentFile>> {
|
||||
let mut segments = Vec::new();
|
||||
if !buffer_dir.exists() {
|
||||
return Ok(segments);
|
||||
}
|
||||
|
||||
for entry in fs::read_dir(buffer_dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|value| value.to_str()) != Some("mp4") {
|
||||
continue;
|
||||
}
|
||||
let metadata = entry.metadata()?;
|
||||
segments.push(SegmentFile {
|
||||
path,
|
||||
modified_at: metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH),
|
||||
});
|
||||
}
|
||||
|
||||
segments.sort_by(|left, right| left.modified_at.cmp(&right.modified_at));
|
||||
Ok(segments)
|
||||
}
|
||||
|
||||
pub fn recent_segments(
|
||||
buffer_dir: &Path,
|
||||
window: Duration,
|
||||
segment_duration: Duration,
|
||||
now: SystemTime,
|
||||
) -> io::Result<Vec<PathBuf>> {
|
||||
let cutoff = now
|
||||
.checked_sub(window + segment_duration)
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
Ok(collect_segments(buffer_dir)?
|
||||
.into_iter()
|
||||
.filter(|segment| segment.modified_at >= cutoff)
|
||||
.map(|segment| segment.path)
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn prune_old_segments(
|
||||
buffer_dir: &Path,
|
||||
replay_window: Duration,
|
||||
segment_duration: Duration,
|
||||
) -> io::Result<usize> {
|
||||
let mut segments = collect_segments(buffer_dir)?;
|
||||
let keep_count =
|
||||
(replay_window.as_secs_f64() / segment_duration.as_secs_f64()).ceil() as usize + 4;
|
||||
if segments.len() <= keep_count {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let remove_count = segments.len() - keep_count;
|
||||
let mut removed = 0;
|
||||
for segment in segments.drain(..remove_count) {
|
||||
fs::remove_file(segment.path)?;
|
||||
removed += 1;
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
pub fn concat_segments(
|
||||
ffmpeg: &Path,
|
||||
segments: &[PathBuf],
|
||||
output: &Path,
|
||||
) -> Result<(), MediaError> {
|
||||
if segments.is_empty() {
|
||||
return Err(MediaError::NoSegments);
|
||||
}
|
||||
if let Some(parent) = output.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
if segments.len() == 1 {
|
||||
fs::copy(&segments[0], output)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let list_path = output.with_extension("concat.txt");
|
||||
let mut list = String::new();
|
||||
for segment in segments {
|
||||
list.push_str("file '");
|
||||
list.push_str(&escape_concat_path(segment));
|
||||
list.push_str("'\n");
|
||||
}
|
||||
fs::write(&list_path, list)?;
|
||||
|
||||
let status = Command::new(ffmpeg)
|
||||
.args([
|
||||
"-y",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-f",
|
||||
"concat",
|
||||
"-safe",
|
||||
"0",
|
||||
"-i",
|
||||
&list_path.display().to_string(),
|
||||
"-c",
|
||||
"copy",
|
||||
&output.display().to_string(),
|
||||
])
|
||||
.status()
|
||||
.map_err(|error| MediaError::Ffmpeg(error.to_string()))?;
|
||||
|
||||
let _ = fs::remove_file(list_path);
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MediaError::Ffmpeg("FFmpeg concat failed".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trim_clip(
|
||||
ffmpeg: &Path,
|
||||
input: &Path,
|
||||
output: &Path,
|
||||
start_seconds: f64,
|
||||
end_seconds: f64,
|
||||
) -> Result<(), MediaError> {
|
||||
if !(end_seconds > start_seconds && start_seconds >= 0.0) {
|
||||
return Err(MediaError::InvalidWindow);
|
||||
}
|
||||
if let Some(parent) = output.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let status = Command::new(ffmpeg)
|
||||
.args([
|
||||
"-y",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-ss",
|
||||
&format!("{start_seconds:.3}"),
|
||||
"-to",
|
||||
&format!("{end_seconds:.3}"),
|
||||
"-i",
|
||||
&input.display().to_string(),
|
||||
"-c",
|
||||
"copy",
|
||||
&output.display().to_string(),
|
||||
])
|
||||
.status()
|
||||
.map_err(|error| MediaError::Ffmpeg(error.to_string()))?;
|
||||
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MediaError::Ffmpeg("FFmpeg trim failed".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_thumbnail(ffmpeg: &Path, input: &Path, output: &Path) -> Result<(), MediaError> {
|
||||
if let Some(parent) = output.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let status = Command::new(ffmpeg)
|
||||
.args([
|
||||
"-y",
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-ss",
|
||||
"00:00:01",
|
||||
"-i",
|
||||
&input.display().to_string(),
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
"3",
|
||||
&output.display().to_string(),
|
||||
])
|
||||
.status()
|
||||
.map_err(|error| MediaError::Ffmpeg(error.to_string()))?;
|
||||
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MediaError::Ffmpeg(
|
||||
"FFmpeg thumbnail generation failed".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn escape_concat_path(path: &Path) -> String {
|
||||
path.display()
|
||||
.to_string()
|
||||
.replace('\\', "/")
|
||||
.replace('\'', "'\\''")
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MediaError {
|
||||
Io(io::Error),
|
||||
Ffmpeg(String),
|
||||
InvalidWindow,
|
||||
NoSegments,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for MediaError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Io(error) => write!(f, "{error}"),
|
||||
Self::Ffmpeg(error) => write!(f, "{error}"),
|
||||
Self::InvalidWindow => f.write_str("clip window is invalid"),
|
||||
Self::NoSegments => f.write_str("no replay buffer segments are available"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for MediaError {
|
||||
fn from(value: io::Error) -> Self {
|
||||
Self::Io(value)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn timestamp_millis(time: SystemTime) -> u128 {
|
||||
time.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn concat_paths_are_ffmpeg_friendly() {
|
||||
let path = Path::new("C:\\clips\\a'b.mp4");
|
||||
assert_eq!(escape_concat_path(path), "C:/clips/a'\\''b.mp4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_keeps_replay_window_plus_slack() {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"clipforge-media-{}",
|
||||
timestamp_millis(SystemTime::now())
|
||||
));
|
||||
fs::create_dir_all(&root).expect("test root");
|
||||
for index in 0..8 {
|
||||
fs::write(root.join(format!("segment-{index}.mp4")), b"x").expect("segment");
|
||||
}
|
||||
|
||||
let removed = prune_old_segments(&root, Duration::from_secs(10), Duration::from_secs(5))
|
||||
.expect("prune");
|
||||
|
||||
assert_eq!(removed, 2);
|
||||
assert_eq!(collect_segments(&root).expect("segments").len(), 6);
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
}
|
||||
+146
-17
@@ -1,5 +1,6 @@
|
||||
use crate::models::UploadProvider;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UploadMetadata {
|
||||
@@ -37,6 +38,17 @@ pub enum UploadError {
|
||||
Provider(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for UploadError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::NotConfigured(message) => write!(f, "{message}"),
|
||||
Self::FileTooLarge { max_mb } => write!(f, "file is larger than {max_mb} MB"),
|
||||
Self::Network(message) => write!(f, "upload network error: {message}"),
|
||||
Self::Provider(message) => write!(f, "upload provider error: {message}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Uploader {
|
||||
fn info(&self) -> UploaderInfo;
|
||||
fn upload(&self, file: &Path, metadata: &UploadMetadata) -> Result<UploadResult, UploadError>;
|
||||
@@ -63,10 +75,31 @@ impl Uploader for CatboxUploader {
|
||||
|
||||
fn upload(&self, file: &Path, _metadata: &UploadMetadata) -> Result<UploadResult, UploadError> {
|
||||
ensure_file_limit(file, 200)?;
|
||||
Err(UploadError::Network(
|
||||
"Catbox upload is wired at the adapter boundary; enable HTTP client dependency for live uploads."
|
||||
.to_string(),
|
||||
))
|
||||
let client = upload_client()?;
|
||||
let file_part = reqwest::blocking::multipart::Part::file(file)
|
||||
.map_err(|error| UploadError::Network(error.to_string()))?;
|
||||
let mut form = reqwest::blocking::multipart::Form::new()
|
||||
.text("reqtype", "fileupload")
|
||||
.part("fileToUpload", file_part);
|
||||
if let Some(userhash) = &self.userhash {
|
||||
if !userhash.trim().is_empty() {
|
||||
form = form.text("userhash", userhash.clone());
|
||||
}
|
||||
}
|
||||
let body = client
|
||||
.post("https://catbox.moe/user/api.php")
|
||||
.multipart(form)
|
||||
.send()
|
||||
.map_err(|error| UploadError::Network(error.to_string()))?
|
||||
.error_for_status()
|
||||
.map_err(|error| UploadError::Provider(error.to_string()))?
|
||||
.text()
|
||||
.map_err(|error| UploadError::Network(error.to_string()))?;
|
||||
let url = parse_plain_url(&body)?;
|
||||
Ok(UploadResult {
|
||||
provider: UploadProvider::Catbox,
|
||||
url,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,10 +131,27 @@ impl Uploader for LitterboxUploader {
|
||||
"Litterbox expiry must be one of 1, 12, 24, or 72 hours.".to_string(),
|
||||
));
|
||||
}
|
||||
Err(UploadError::Network(
|
||||
"Litterbox upload is wired at the adapter boundary; enable HTTP client dependency for live uploads."
|
||||
.to_string(),
|
||||
))
|
||||
let client = upload_client()?;
|
||||
let file_part = reqwest::blocking::multipart::Part::file(file)
|
||||
.map_err(|error| UploadError::Network(error.to_string()))?;
|
||||
let form = reqwest::blocking::multipart::Form::new()
|
||||
.text("reqtype", "fileupload")
|
||||
.text("time", format!("{}h", self.expiry_hours))
|
||||
.part("fileToUpload", file_part);
|
||||
let body = client
|
||||
.post("https://litterbox.catbox.moe/resources/internals/api.php")
|
||||
.multipart(form)
|
||||
.send()
|
||||
.map_err(|error| UploadError::Network(error.to_string()))?
|
||||
.error_for_status()
|
||||
.map_err(|error| UploadError::Provider(error.to_string()))?
|
||||
.text()
|
||||
.map_err(|error| UploadError::Network(error.to_string()))?;
|
||||
let url = parse_plain_url(&body)?;
|
||||
Ok(UploadResult {
|
||||
provider: UploadProvider::Litterbox,
|
||||
url,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,6 +161,7 @@ pub struct CustomHttpUploader {
|
||||
pub method: String,
|
||||
pub multipart_field: String,
|
||||
pub response_url_path: String,
|
||||
pub headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Uploader for CustomHttpUploader {
|
||||
@@ -127,20 +178,52 @@ impl Uploader for CustomHttpUploader {
|
||||
}
|
||||
}
|
||||
|
||||
fn upload(
|
||||
&self,
|
||||
_file: &Path,
|
||||
_metadata: &UploadMetadata,
|
||||
) -> Result<UploadResult, UploadError> {
|
||||
fn upload(&self, file: &Path, metadata: &UploadMetadata) -> Result<UploadResult, UploadError> {
|
||||
if self.endpoint.trim().is_empty() {
|
||||
return Err(UploadError::NotConfigured(
|
||||
"custom upload endpoint is required".to_string(),
|
||||
));
|
||||
}
|
||||
Err(UploadError::Network(
|
||||
"Custom upload is configured; enable HTTP client dependency for live uploads."
|
||||
.to_string(),
|
||||
))
|
||||
if !self.method.eq_ignore_ascii_case("POST") {
|
||||
return Err(UploadError::Provider(
|
||||
"custom uploads currently support POST multipart requests".to_string(),
|
||||
));
|
||||
}
|
||||
let client = upload_client()?;
|
||||
let file_part = reqwest::blocking::multipart::Part::file(file)
|
||||
.map_err(|error| UploadError::Network(error.to_string()))?;
|
||||
let field_name = if self.multipart_field.trim().is_empty() {
|
||||
"file"
|
||||
} else {
|
||||
self.multipart_field.trim()
|
||||
};
|
||||
let form = reqwest::blocking::multipart::Form::new()
|
||||
.text("clip_id", metadata.clip_id.clone())
|
||||
.text("game_id", metadata.game_id.clone())
|
||||
.text("title", metadata.title.clone())
|
||||
.part(field_name.to_string(), file_part);
|
||||
let mut request = client.post(&self.endpoint).multipart(form);
|
||||
for (name, value) in &self.headers {
|
||||
if !name.trim().is_empty() {
|
||||
request = request.header(name, value);
|
||||
}
|
||||
}
|
||||
let body = request
|
||||
.send()
|
||||
.map_err(|error| UploadError::Network(error.to_string()))?
|
||||
.error_for_status()
|
||||
.map_err(|error| UploadError::Provider(error.to_string()))?
|
||||
.text()
|
||||
.map_err(|error| UploadError::Network(error.to_string()))?;
|
||||
let url = if self.response_url_path.trim().is_empty() {
|
||||
parse_plain_url(&body)?
|
||||
} else {
|
||||
extract_json_path(&body, &self.response_url_path)?
|
||||
};
|
||||
Ok(UploadResult {
|
||||
provider: UploadProvider::CustomHttp,
|
||||
url,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,6 +261,42 @@ fn ensure_file_limit(file: &Path, max_mb: u64) -> Result<(), UploadError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn upload_client() -> Result<reqwest::blocking::Client, UploadError> {
|
||||
reqwest::blocking::Client::builder()
|
||||
.timeout(Duration::from_secs(120))
|
||||
.user_agent("ClipForge/0.1")
|
||||
.build()
|
||||
.map_err(|error| UploadError::Network(error.to_string()))
|
||||
}
|
||||
|
||||
fn parse_plain_url(body: &str) -> Result<String, UploadError> {
|
||||
let trimmed = body.trim();
|
||||
if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
|
||||
Ok(trimmed.to_string())
|
||||
} else {
|
||||
Err(UploadError::Provider(trimmed.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_json_path(body: &str, path: &str) -> Result<String, UploadError> {
|
||||
let mut value: &serde_json::Value = &serde_json::from_str(body)
|
||||
.map_err(|error| UploadError::Provider(format!("invalid JSON response: {error}")))?;
|
||||
for key in path.trim().trim_start_matches("$.").split('.') {
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
value = value.get(key).ok_or_else(|| {
|
||||
UploadError::Provider(format!("response URL path was not found: {path}"))
|
||||
})?;
|
||||
}
|
||||
let Some(url) = value.as_str() else {
|
||||
return Err(UploadError::Provider(format!(
|
||||
"response URL path is not a string: {path}"
|
||||
)));
|
||||
};
|
||||
parse_plain_url(url)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -196,4 +315,14 @@ mod tests {
|
||||
|
||||
assert!(matches!(result, Err(UploadError::Provider(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_custom_json_url_path() {
|
||||
let url = extract_json_path(
|
||||
r#"{"data":{"url":"https://example.test/c.mp4"}}"#,
|
||||
"data.url",
|
||||
)
|
||||
.expect("url");
|
||||
assert_eq!(url, "https://example.test/c.mp4");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user