Spaces:
Sleeping
Sleeping
Download src/transcoder.rs from MonteeqOrg/README: direct link, hf CLI and curl.
- Browser
- Download file 33.7 kB
-
https://huggingface.co/spaces/MonteeqOrg/README/resolve/main/src/transcoder.rs
- Command line
-
hf download hf://spaces/MonteeqOrg/README/src/transcoder.rs
-
curl -L -o transcoder.rs https://huggingface.co/spaces/MonteeqOrg/README/resolve/main/src/transcoder.rs
33.7 kB
use tokio::process::Command;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
use fred::interfaces::KeysInterface;
use anyhow::{Result, anyhow};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tokio::fs;
use tokio::task::JoinSet;
use crate::storage::StorageManager;
use crate::models::{UserTier, TaskStatus};
use crate::queue::WeightedScheduler;
/// Redis key TTL for live encode progress (seconds).
const JOB_PROGRESS_TTL_SECS: i64 = 300;
/// Minimum gap between progress Redis writes.
const PROGRESS_REPORT_INTERVAL: Duration = Duration::from_secs(1);
/// Target HLS segment length.
const HLS_SEGMENT_SECS: u32 = 6;
/// Progress band: encode starts at 15% and may not exceed this.
const ENCODE_BASE_PCT: u32 = 15;
const ENCODE_SPAN_PCT: u32 = 75;
pub struct TranscodingConfig {
pub preset: String,
pub crf: String,
}
impl TranscodingConfig {
pub fn for_tier(tier: &UserTier) -> Self {
match tier {
UserTier::Free => Self {
preset: "ultrafast".to_string(),
crf: "26".to_string(), // Slightly lower quality for space/speed
},
UserTier::Pro => Self {
preset: "medium".to_string(),
crf: "23".to_string(), // Better quality
},
}
}
}
/// Highest rendition we consider a "passthrough" candidate per tier. A source
/// that already fits the cap and is H.264/AAC does not need re-encoding at all.
fn passthrough_cap(tier: &UserTier) -> i32 {
match tier {
UserTier::Free => 720,
UserTier::Pro => 1080,
}
}
fn job_progress_key(job_id: &str) -> String {
format!("job:progress:{}", job_id)
}
/// Write live encode progress `0..=100` to `job:progress:{job_id}` (fred Redis client).
pub async fn set_job_progress(sched: &WeightedScheduler, job_id: &str, percent: u32) {
let pct = percent.min(100);
let _: () = sched
.client()
.set(
job_progress_key(job_id),
pct.to_string(),
Some(fred::types::Expiration::EX(JOB_PROGRESS_TTL_SECS)),
None,
false,
)
.await
.unwrap_or_default();
}
/// Remove progress key so failed jobs do not leave a stale percentage.
pub async fn clear_job_progress(sched: &WeightedScheduler, job_id: &str) {
let _: () = sched
.client()
.del(job_progress_key(job_id))
.await
.unwrap_or_default();
}
/// Everything one ffprobe invocation can tell us about the source.
#[derive(Debug, Clone)]
struct Probe {
width: i32,
height: i32,
has_audio: bool,
duration: f64,
video_codec: String,
audio_codec: Option<String>,
}
impl Probe {
/// True when the video/audio streams can be copied into HLS untouched.
fn copy_safe(&self) -> bool {
self.video_codec.eq_ignore_ascii_case("h264")
&& self
.audio_codec
.as_deref()
.map(|c| c.eq_ignore_ascii_case("aac"))
.unwrap_or(true)
}
}
/// One output rendition.
#[derive(Debug, Clone)]
struct Variant {
name: String,
height: i32,
bitrate: &'static str,
}
fn bitrate_for(height: i32) -> &'static str {
if height >= 1080 {
"5000k"
} else if height >= 720 {
"2800k"
} else {
"1200k"
}
}
fn label_for(height: i32) -> &'static str {
if height >= 1080 {
"1080p"
} else if height >= 720 {
"720p"
} else {
"480p"
}
}
/// Decide the rendition set.
///
/// Rules, in priority order:
/// 1. Source already H.264/AAC and inside the tier cap → single passthrough
/// variant at native resolution (no encode at all).
/// 2. Flash → single variant at native resolution ("original").
/// 3. Otherwise → ladder capped by tier, filtered against the source so we
/// never upscale. Free tier produces a single rendition; Pro keeps the
/// 1080/720/480 ladder.
fn plan_variants(format: &str, tier: &UserTier, probe: &Probe) -> (Vec<Variant>, bool) {
let cap = passthrough_cap(tier);
if probe.copy_safe() && probe.height <= cap {
let name = if format == "flash" {
"original".to_string()
} else {
label_for(probe.height).to_string()
};
return (
vec![Variant {
name,
height: probe.height,
bitrate: bitrate_for(probe.height),
}],
true,
);
}
if format == "flash" {
return (
vec![Variant {
name: "original".to_string(),
height: probe.height,
bitrate: bitrate_for(probe.height),
}],
false,
);
}
let top = match tier {
UserTier::Pro => 1080,
UserTier::Free => 720,
};
// Free tier: one rendition at the source height, capped. Encoding the whole
// ladder is what made 2-vCPU Spaces crawl.
if matches!(tier, UserTier::Free) {
let h = probe.height.min(top).max(2);
return (
vec![Variant {
name: label_for(h).to_string(),
height: h,
bitrate: bitrate_for(h),
}],
false,
);
}
let mut variants: Vec<Variant> = Vec::new();
for h in [1080, 720, 480] {
if h <= top && probe.height >= h {
variants.push(Variant {
name: format!("{}p", h),
height: h,
bitrate: bitrate_for(h),
});
}
}
// Source smaller than every ladder step: keep one rendition at the source
// height (never upscale) and name it after the bucket it falls into.
if variants.is_empty() {
let h = probe.height.min(top).max(2);
variants.push(Variant {
name: label_for(h).to_string(),
height: h,
bitrate: bitrate_for(h),
});
}
(variants, false)
}
/// Encode (or remux) into HLS, uploading segments while ffmpeg is still running,
/// then generate the cover. Returns the output directory.
#[allow(clippy::too_many_arguments)]
pub async fn process(
_video_id: String, // Platform ID
video_path: &str, // Local filesystem path
format: &str,
tier: UserTier,
skip_thumbnail: bool,
scheduler: Option<WeightedScheduler>,
task_id: String,
storage: Arc<StorageManager>,
) -> Result<(String, Vec<String>)> {
println!(
"Starting processing for task_id={} video_path={}",
task_id, video_path
);
// Check if file exists
if !Path::new(video_path).exists() {
return Err(anyhow!("Video file not found at path: {}", video_path));
}
let config = TranscodingConfig::for_tier(&tier);
status(
scheduler.as_ref(),
&task_id,
5,
"Analyzing video streams and metadata...",
)
.await;
let probe = match probe_video(video_path).await {
Ok(p) => p,
Err(e) => {
eprintln!("Metadata extraction failed for {}: {}", video_path, e);
if let Some(ref sched) = scheduler {
clear_job_progress(sched, &task_id).await;
}
return Err(e);
}
};
println!(
"Metadata: width={} height={} has_audio={} duration={:.3}s codec={} audio={:?}",
probe.width,
probe.height,
probe.has_audio,
probe.duration,
probe.video_codec,
probe.audio_codec
);
// ── Orientation validation ────────────────────────────────────────────────
// Reject jobs whose declared format (home/flash) does not match actual pixel
// dimensions. Square-ish videos (aspect 0.9–1.1) always pass regardless of
// declared type. This catches client-side bypasses (devtools, direct API).
{
let ratio = probe.width as f64 / probe.height as f64;
let is_squareish = ratio >= 0.9 && ratio <= 1.1;
if !is_squareish {
let mismatch = match format {
"flash" => ratio > 1.1, // declared flash but video is landscape
"home" => ratio < 0.9, // declared home but video is portrait
_ => false,
};
if mismatch {
let msg = format!(
"Video orientation doesn't match the selected format: \
video is {}x{} ({} {}) but format is \"{}\"",
probe.width,
probe.height,
if ratio > 1.1 { "landscape" } else { "portrait" },
ratio,
format,
);
eprintln!("{}", msg);
if let Some(ref sched) = scheduler {
clear_job_progress(sched, &task_id).await;
}
return Err(anyhow!("{}", msg));
}
}
}
// 2. Prep Output — wipe leftovers from a previous attempt so a retry can
// never upload stale segments alongside fresh ones.
let output_dir = format!("{}_hls", video_path);
if Path::new(&output_dir).exists() {
fs::remove_dir_all(&output_dir).await.ok();
}
fs::create_dir_all(&output_dir).await?;
let (variants, copy) = plan_variants(format, &tier, &probe);
let variant_names: Vec<String> = variants.iter().map(|v| v.name.clone()).collect();
println!(
"Plan: variants={:?} mode={}",
variant_names,
if copy { "remux" } else { "encode" }
);
// 3. Start uploading segments as they appear — no post-encode tail.
let s3_prefix = format!("videos/{}", task_id);
let uploader = DirUploader::start(storage.clone(), output_dir.clone(), s3_prefix.clone());
status(
scheduler.as_ref(),
&task_id,
ENCODE_BASE_PCT,
if copy {
"Packaging video into adaptive streams..."
} else {
"Compressing and optimizing video..."
},
)
.await;
let args = build_args(video_path, &output_dir, &probe, &variants, copy, &config);
let encode_res = run_ffmpeg_with_progress(
&args,
probe.duration,
scheduler.as_ref(),
&task_id,
ENCODE_BASE_PCT,
ENCODE_SPAN_PCT,
)
.await;
// Drain whatever ffmpeg just wrote (playlists land at the end).
let upload_res = uploader.finish().await;
if let Err(e) = encode_res {
if let Some(ref sched) = scheduler {
clear_job_progress(sched, &task_id).await;
}
return Err(e);
}
upload_res?;
// 4. Thumbnail next to the source (legacy path; auto-cover is handled by the worker)
if !skip_thumbnail {
status(scheduler.as_ref(), &task_id, 92, "Generating thumbnail...").await;
if let Err(e) = generate_thumbnail(video_path).await {
eprintln!("Legacy thumbnail generation failed: {}", e);
}
}
Ok((output_dir, variant_names))
}
async fn status(
scheduler: Option<&WeightedScheduler>,
task_id: &str,
progress: u32,
message: &str,
) {
if let Some(sched) = scheduler {
let status = TaskStatus {
progress,
status: "processing".to_string(),
message: message.to_string(),
cover_url: None,
cover_source: None,
variants: None,
};
let status_json = serde_json::to_string(&status).unwrap_or_default();
let _: () = sched
.client()
.set(
format!("task:status:{}", task_id),
status_json,
Some(fred::types::Expiration::EX(86400)),
None,
false,
)
.await
.unwrap_or_default();
}
}
/// Build the ffmpeg invocation for either a remux (`copy = true`) or a real encode.
fn build_args(
input: &str,
output_dir: &str,
probe: &Probe,
variants: &[Variant],
copy: bool,
config: &TranscodingConfig,
) -> Vec<String> {
let n = variants.len();
let mut args: Vec<String> = vec!["-i".into(), input.into()];
if !copy {
args.extend([
"-preset".to_string(),
config.preset.clone(),
"-crf".to_string(),
config.crf.clone(),
]);
}
args.extend([
"-f".into(),
"hls".into(),
"-hls_time".into(),
HLS_SEGMENT_SECS.to_string(),
"-hls_playlist_type".into(),
"vod".into(),
"-master_pl_name".into(),
"master.m3u8".into(),
]);
// Threads per encoder: with several renditions in one process, letting each
// x264 instance spawn for every core oversubscribes a 2-vCPU Space.
let cores = std::thread::available_parallelism()
.map(|c| c.get())
.unwrap_or(2);
let threads_per_variant = (cores / n.max(1)).max(1);
if copy {
args.extend(["-map".into(), "0:v:0".into()]);
args.extend(["-c".into(), "copy".into()]);
} else if n == 1 {
let filter = format!("[0:v]scale=w=-2:h={}[v0out]", variants[0].height);
args.extend(["-filter_complex".into(), filter]);
args.extend([
"-map".into(),
"[v0out]".into(),
"-c:v:0".into(),
"libx264".into(),
"-b:v:0".into(),
variants[0].bitrate.to_string(),
"-threads:v:0".to_string(),
threads_per_variant.to_string(),
]);
} else {
let mut filter = format!("[0:v]split={}", n);
for i in 0..n {
filter.push_str(&format!("[v{}]", i));
}
filter.push(';');
for i in 0..n {
filter.push_str(&format!(
" [v{}]scale=w=-2:h={}[v{}out];",
i, variants[i].height, i
));
}
args.extend(["-filter_complex".into(), filter]);
for (i, variant) in variants.iter().enumerate() {
args.extend([
"-map".to_string(),
format!("[v{}out]", i),
format!("-c:v:{}", i),
"libx264".to_string(),
format!("-b:v:{}", i),
variant.bitrate.to_string(),
format!("-threads:v:{}", i),
threads_per_variant.to_string(),
]);
}
}
// ── Audio ────────────────────────────────────────────────────────────────
// Each HLS variant needs its OWN audio output stream. Map the source audio
// once per variant with unique a:N so the muxer writes independent AAC
// streams into each segment set. Copy mode keeps the source audio codec.
if probe.has_audio {
for _ in 0..n {
args.push("-map".into());
args.push("0:a:0".into());
}
if !copy {
for i in 0..n {
args.push(format!("-c:a:{}", i));
args.push("aac".into());
args.push(format!("-b:a:{}", i));
args.push("128k".into());
}
}
}
// ── HLS naming ───────────────────────────────────────────────────────────
let stream_map = if probe.has_audio {
variants
.iter()
.enumerate()
.map(|(i, v)| format!("v:{},a:{},name:{}", i, i, v.name))
.collect::<Vec<_>>()
.join(" ")
} else {
variants
.iter()
.enumerate()
.map(|(i, v)| format!("v:{},name:{}", i, v.name))
.collect::<Vec<_>>()
.join(" ")
};
args.extend([
"-hls_segment_filename".to_string(),
format!("{}/%v_%03d.ts", output_dir),
"-var_stream_map".to_string(),
stream_map,
format!("{}/%v.m3u8", output_dir),
]);
args
}
/// Spawn ffmpeg with `-progress pipe:1`, map `out_time` onto the `base..base+span`
/// progress band, and throttle Redis writes to ~1/sec.
async fn run_ffmpeg_with_progress(
args: &[String],
duration_secs: f64,
scheduler: Option<&WeightedScheduler>,
task_id: &str,
base: u32,
span: u32,
) -> Result<()> {
// Machine-readable progress on stdout; keep stderr for errors (drained so the pipe never blocks).
let mut full_args: Vec<String> = vec![
"-nostats".into(),
"-progress".into(),
"pipe:1".into(),
];
full_args.extend(args.iter().cloned());
let mut child = Command::new("ffmpeg")
.args(&full_args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let stdout = child
.stdout
.take()
.ok_or_else(|| anyhow!("ffmpeg stdout not captured"))?;
let stderr = child
.stderr
.take()
.ok_or_else(|| anyhow!("ffmpeg stderr not captured"))?;
let stderr_task = tokio::spawn(async move {
let mut buf = Vec::new();
let mut reader = BufReader::new(stderr);
let _ = reader.read_to_end(&mut buf).await;
String::from_utf8_lossy(&buf).to_string()
});
let mut lines = BufReader::new(stdout).lines();
let mut last_report = Instant::now()
.checked_sub(PROGRESS_REPORT_INTERVAL)
.unwrap_or_else(Instant::now);
let mut current_out_us: u64 = 0;
while let Some(line) = lines.next_line().await? {
let line = line.trim();
if let Some(v) = line.strip_prefix("out_time_us=") {
if let Ok(us) = v.parse::<u64>() {
current_out_us = us;
}
} else if let Some(v) = line.strip_prefix("out_time_ms=") {
// Historical ffmpeg key: value is microseconds despite the name.
if let Ok(us) = v.parse::<u64>() {
current_out_us = us;
}
} else if line.starts_with("progress=") {
let force = line == "progress=end";
if force || last_report.elapsed() >= PROGRESS_REPORT_INTERVAL {
if duration_secs > 0.0 {
let current_time_seconds = current_out_us as f64 / 1_000_000.0;
let ratio = (current_time_seconds / duration_secs).clamp(0.0, 1.0);
// Stay below base+span until process exit confirms success.
let progress_percent = base + (ratio * span as f64) as u32;
if let Some(sched) = scheduler {
set_job_progress(sched, task_id, progress_percent).await;
}
}
last_report = Instant::now();
}
}
}
let status = child.wait().await?;
let err_text = stderr_task.await.unwrap_or_default();
if !status.success() {
eprintln!("FFmpeg Error: {}", err_text);
if let Some(sched) = scheduler {
clear_job_progress(sched, task_id).await;
}
return Err(anyhow!("FFmpeg failed: {}", err_text));
}
Ok(())
}
/// Background directory watcher: uploads each HLS artifact as soon as its size
/// stops changing, so S3 transfer overlaps the encode instead of following it.
struct DirUploader {
stop: Arc<AtomicBool>,
handle: tokio::task::JoinHandle<Result<()>>,
}
impl DirUploader {
fn start(storage: Arc<StorageManager>, dir: String, prefix: String) -> Self {
let stop = Arc::new(AtomicBool::new(false));
let handle = tokio::spawn({
let stop = stop.clone();
async move { run_dir_uploader(storage, dir, prefix, stop).await }
});
Self { stop, handle }
}
async fn finish(self) -> Result<()> {
self.stop.store(true, Ordering::Relaxed);
match self.handle.await {
Ok(res) => res,
Err(e) => Err(anyhow!("segment uploader panicked: {}", e)),
}
}
}
async fn run_dir_uploader(
storage: Arc<StorageManager>,
dir: String,
prefix: String,
stop: Arc<AtomicBool>,
) -> Result<()> {
let concurrency = std::env::var("UPLOAD_CONCURRENCY")
.ok()
.and_then(|v| v.parse::<usize>().ok())
.filter(|v| *v > 0)
.unwrap_or(12);
// name -> last observed size. A file is uploaded once its size is stable
// across two polls (i.e. ffmpeg has finished writing it).
let mut sizes: HashMap<String, u64> = HashMap::new();
let mut queued: HashSet<String> = HashSet::new();
let mut inflight: JoinSet<Result<()>> = JoinSet::new();
let mut first_err: Option<anyhow::Error> = None;
loop {
while let Some(res) = inflight.try_join_next() {
match res {
Ok(Ok(())) => {}
Ok(Err(e)) => {
if first_err.is_none() {
first_err = Some(e);
}
}
Err(e) => {
if first_err.is_none() {
first_err = Some(anyhow!("upload task failed: {}", e));
}
}
}
}
let stopping = stop.load(Ordering::Relaxed);
if inflight.len() < concurrency {
if let Ok(mut entries) = fs::read_dir(&dir).await {
loop {
let entry = match entries.next_entry().await {
Ok(Some(e)) => e,
Ok(None) => break,
Err(_) => break,
};
let path = entry.path();
if !path.is_file() {
continue;
}
let name = match path.file_name().and_then(|n| n.to_str()) {
Some(n) => n.to_string(),
None => continue,
};
if queued.contains(&name) {
continue;
}
let size = entry.metadata().await.map(|m| m.len()).unwrap_or(0);
let stable = sizes.get(&name) == Some(&size);
sizes.insert(name.clone(), size);
// Skip files ffmpeg is still growing (and empty placeholders).
if (!stable && !stopping) || size == 0 {
continue;
}
queued.insert(name.clone());
let storage = storage.clone();
let key = format!("{}/{}", prefix, name);
inflight.spawn(async move { storage.upload_file(&path, &key).await });
}
}
}
if stopping && inflight.is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
match first_err {
Some(e) => Err(e),
None => Ok(()),
}
}
/// Probe width/height/audio/duration/codecs in a single ffprobe invocation.
async fn probe_video(video_path: &str) -> Result<Probe> {
let output = Command::new("ffprobe")
.args([
"-v",
"error",
"-show_entries",
"stream=codec_type,codec_name,width,height:format=duration",
"-of",
"json",
video_path,
])
.output()
.await?;
if !output.status.success() {
return Err(anyhow!(
"ffprobe failed for {}: {}",
video_path,
String::from_utf8_lossy(&output.stderr).trim()
));
}
let raw = String::from_utf8_lossy(&output.stdout);
let json: serde_json::Value = serde_json::from_str(&raw)
.map_err(|e| anyhow!("Invalid ffprobe JSON ({}): {}", e, raw.trim()))?;
let duration = json
.get("format")
.and_then(|f| f.get("duration"))
.and_then(|d| d.as_str())
.and_then(|d| d.parse::<f64>().ok())
.filter(|d| d.is_finite() && *d > 0.0)
.unwrap_or(0.0);
let streams = json
.get("streams")
.and_then(|v| v.as_array())
.ok_or_else(|| anyhow!("ffprobe returned no streams: {}", raw.trim()))?;
let mut width = 0i32;
let mut height = 0i32;
let mut video_codec = String::new();
let mut audio_codec: Option<String> = None;
let mut has_audio = false;
for stream in streams {
let kind = stream.get("codec_type").and_then(|v| v.as_str()).unwrap_or("");
match kind {
"video" if width == 0 => {
let w = stream.get("width").and_then(|v| v.as_i64()).unwrap_or(0);
let h = stream.get("height").and_then(|v| v.as_i64()).unwrap_or(0);
if w > 0 && h > 0 {
width = w as i32;
height = h as i32;
video_codec = stream
.get("codec_name")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
}
}
"audio" if !has_audio => {
has_audio = true;
audio_codec = stream
.get("codec_name")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
}
_ => {}
}
}
if width == 0 || height == 0 {
return Err(anyhow!(
"ffprobe returned no usable width/height: {}",
raw.trim()
));
}
Ok(Probe {
width,
height,
has_audio,
duration,
video_codec,
audio_codec,
})
}
/// Pick the first width/height pair from `ffprobe -of json -show_entries stream=width,height`.
///
/// JSON is used instead of `-of csv=s=x:p=0` because the CSV writer can emit
/// extra sections/fields depending on the container (e.g. QuickTime timecode
/// tracks and MPEG-TS programs produce multiple lines, and some files end with
/// a bare separator like `1080x1080x`). Splitting the whole stdout on 'x' then
/// rejects perfectly valid values.
#[cfg(test)]
fn parse_dimensions(stdout: &[u8]) -> Result<(i32, i32)> {
let raw = String::from_utf8_lossy(stdout);
let json: serde_json::Value = serde_json::from_str(&raw)
.map_err(|e| anyhow!("Invalid ffprobe JSON ({}): {}", e, raw.trim()))?;
let streams = json
.get("streams")
.and_then(|v| v.as_array())
.ok_or_else(|| anyhow!("ffprobe returned no streams: {}", raw.trim()))?;
for stream in streams {
let width = stream.get("width").and_then(|v| v.as_i64());
let height = stream.get("height").and_then(|v| v.as_i64());
if let (Some(w), Some(h)) = (width, height) {
if w > 0 && h > 0 {
return Ok((w as i32, h as i32));
}
}
}
Err(anyhow!(
"ffprobe returned no usable width/height: {}",
raw.trim()
))
}
async fn generate_thumbnail(video_path: &str) -> Result<()> {
// Legacy path (thumbnails next to source). Prefer generate_and_upload_auto_cover.
let thumb_path = format!("{}.jpg", video_path);
extract_cover_frame(video_path, &thumb_path, 0.1).await
}
/// Seek ~`pct` into the video (default 10%) and write a single JPEG frame.
pub async fn extract_cover_frame(video_path: &str, out_jpg: &str, pct: f64) -> Result<()> {
let duration = probe_video(video_path)
.await
.map(|p| p.duration)
.unwrap_or(0.0);
let seek_secs = if duration > 0.5 {
(duration * pct).clamp(0.0, (duration - 0.05).max(0.0))
} else {
0.0
};
let seek_arg = format!("{:.3}", seek_secs);
println!(
"Extracting cover frame from {} at {}s ({:.0}% of {:.2}s) → {}",
video_path,
seek_arg,
pct * 100.0,
duration,
out_jpg
);
let status = Command::new("ffmpeg")
.args(&[
"-ss",
&seek_arg,
"-i",
video_path,
"-frames:v",
"1",
"-update",
"1",
"-q:v",
"2",
"-y",
out_jpg,
])
.status()
.await?;
if !status.success() {
return Err(anyhow!("Cover frame extraction failed"));
}
if !Path::new(out_jpg).exists() {
return Err(anyhow!("Cover JPEG was not written: {}", out_jpg));
}
Ok(())
}
/// Auto cover: frame at ~10% duration → JPEG → S3 `thumbnails/{task_id}.jpg`.
///
/// Prefers pulling the frame out of an already-encoded HLS segment (cheap, and
/// the bytes are already local) and only falls back to re-reading the source.
/// Returns the S3 key for inclusion in the Redis completion payload.
pub async fn generate_and_upload_auto_cover(
video_path: &str,
output_dir: &str,
task_id: &str,
storage: &StorageManager,
) -> Result<String> {
let cover_local = format!("{}_cover.jpg", video_path);
let source = pick_cover_source(video_path, output_dir).await;
extract_cover_frame(&source, &cover_local, 0.1).await?;
let cover_key = format!("thumbnails/{}.jpg", task_id);
storage
.upload_file(Path::new(&cover_local), &cover_key)
.await?;
// Best-effort cleanup of local JPEG
let _ = fs::remove_file(&cover_local).await;
println!("Auto cover uploaded: {}", cover_key);
Ok(cover_key)
}
/// Choose the cheapest file that contains a representative frame.
async fn pick_cover_source(video_path: &str, output_dir: &str) -> String {
let entries = match fs::read_dir(output_dir).await {
Ok(e) => e,
Err(_) => return video_path.to_string(),
};
let mut segments: Vec<(u32, std::path::PathBuf)> = Vec::new();
let mut entries = entries;
while let Ok(Some(entry)) = entries.next_entry().await {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("ts") {
continue;
}
let name = match path.file_name().and_then(|n| n.to_str()) {
Some(n) => n,
None => continue,
};
// "<variant>_<index>.ts"
if let Some(idx) = name
.rsplit_once('_')
.and_then(|(_, tail)| tail.trim_end_matches(".ts").parse::<u32>().ok())
{
segments.push((idx, path));
}
}
if segments.is_empty() {
return video_path.to_string();
}
// Roughly 10% into the video, expressed in segments.
let total = segments.iter().map(|(i, _)| *i).max().unwrap_or(0) + 1;
let target = (total / 10).min(total.saturating_sub(1));
segments.sort_by_key(|(idx, _)| idx.abs_diff(target));
segments
.into_iter()
.next()
.map(|(_, p)| p.to_string_lossy().to_string())
.unwrap_or_else(|| video_path.to_string())
}
#[cfg(test)]
mod tests {
use super::{label_for, parse_dimensions, plan_variants, Probe, UserTier};
fn probe(height: i32, codec: &str) -> Probe {
Probe {
width: (height as f64 * 16.0 / 9.0) as i32,
height,
has_audio: true,
duration: 60.0,
video_codec: codec.to_string(),
audio_codec: Some("aac".to_string()),
}
}
#[test]
fn picks_first_stream_with_dimensions() {
// `programs` is emitted too for some containers; top-level `streams` wins.
let out = br#"{
"programs":[{"streams":[{"width":640,"height":480}]}],
"streams":[{"width":1080,"height":1080},{"codec_type":"audio"}]
}"#;
assert_eq!(parse_dimensions(out).unwrap(), (1080, 1080));
}
#[test]
fn skips_streams_without_dimensions() {
let out = br#"{"streams":[{"codec_type":"video"},{"width":720,"height":1280}]}"#;
assert_eq!(parse_dimensions(out).unwrap(), (720, 1280));
}
#[test]
fn rejects_zero_dimensions() {
let out = br#"{"streams":[{"width":0,"height":0}]}"#;
assert!(parse_dimensions(out).is_err());
}
#[test]
fn rejects_non_json_output() {
assert!(parse_dimensions(b"1080x1080x").is_err());
}
#[test]
fn h264_within_cap_is_passthrough() {
let (variants, copy) = plan_variants("home", &UserTier::Free, &probe(720, "h264"));
assert!(copy);
assert_eq!(variants.len(), 1);
assert_eq!(variants[0].name, "720p");
}
#[test]
fn h264_above_cap_must_encode() {
let (variants, copy) = plan_variants("home", &UserTier::Free, &probe(1080, "h264"));
assert!(!copy);
assert_eq!(variants.len(), 1);
assert_eq!(variants[0].height, 720);
}
#[test]
fn low_resolution_source_is_never_upscaled() {
let (variants, _) = plan_variants("home", &UserTier::Free, &probe(360, "hevc"));
assert_eq!(variants.len(), 1);
assert_eq!(variants[0].height, 360);
}
#[test]
fn pro_keeps_the_ladder() {
let (variants, _) = plan_variants("home", &UserTier::Pro, &probe(1080, "hevc"));
let names: Vec<_> = variants.iter().map(|v| v.name.as_str()).collect();
assert_eq!(names, vec!["1080p", "720p", "480p"]);
}
#[test]
fn labels_bucket_by_height() {
assert_eq!(label_for(1080), "1080p");
assert_eq!(label_for(720), "720p");
assert_eq!(label_for(360), "480p");
}
}
use tokio::process::Command;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
use fred::interfaces::KeysInterface;
use anyhow::{Result, anyhow};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tokio::fs;
use tokio::task::JoinSet;
use crate::storage::StorageManager;
use crate::models::{UserTier, TaskStatus};
use crate::queue::WeightedScheduler;
/// Redis key TTL for live encode progress (seconds).
const JOB_PROGRESS_TTL_SECS: i64 = 300;
/// Minimum gap between progress Redis writes.
const PROGRESS_REPORT_INTERVAL: Duration = Duration::from_secs(1);
/// Target HLS segment length.
const HLS_SEGMENT_SECS: u32 = 6;
/// Progress band: encode starts at 15% and may not exceed this.
const ENCODE_BASE_PCT: u32 = 15;
const ENCODE_SPAN_PCT: u32 = 75;
pub struct TranscodingConfig {
pub preset: String,
pub crf: String,
}
impl TranscodingConfig {
pub fn for_tier(tier: &UserTier) -> Self {
match tier {
UserTier::Free => Self {
preset: "ultrafast".to_string(),
crf: "26".to_string(), // Slightly lower quality for space/speed
},
UserTier::Pro => Self {
preset: "medium".to_string(),
crf: "23".to_string(), // Better quality
},
}
}
}
/// Highest rendition we consider a "passthrough" candidate per tier. A source
/// that already fits the cap and is H.264/AAC does not need re-encoding at all.
fn passthrough_cap(tier: &UserTier) -> i32 {
match tier {
UserTier::Free => 720,
UserTier::Pro => 1080,
}
}
fn job_progress_key(job_id: &str) -> String {
format!("job:progress:{}", job_id)
}
/// Write live encode progress `0..=100` to `job:progress:{job_id}` (fred Redis client).
pub async fn set_job_progress(sched: &WeightedScheduler, job_id: &str, percent: u32) {
let pct = percent.min(100);
let _: () = sched
.client()
.set(
job_progress_key(job_id),
pct.to_string(),
Some(fred::types::Expiration::EX(JOB_PROGRESS_TTL_SECS)),
None,
false,
)
.await
.unwrap_or_default();
}
/// Remove progress key so failed jobs do not leave a stale percentage.
pub async fn clear_job_progress(sched: &WeightedScheduler, job_id: &str) {
let _: () = sched
.client()
.del(job_progress_key(job_id))
.await
.unwrap_or_default();
}
/// Everything one ffprobe invocation can tell us about the source.
struct Probe {
width: i32,
height: i32,
has_audio: bool,
duration: f64,
video_codec: String,
audio_codec: Option<String>,
}
impl Probe {
/// True when the video/audio streams can be copied into HLS untouched.
fn copy_safe(&self) -> bool {
self.video_codec.eq_ignore_ascii_case("h264")
&& self