Monteeq CI commited on
Commit
a8673cc
·
1 Parent(s): 65bc393

🚀 Deploy from GitHub @ 4eb79b5e42a5d81d582a63b79ba4afd35d266c0b

Browse files

Triggered by: Smasduq
Message: Speed up video processing pipeline

Encoding:
- Remux H.264/AAC sources that fit the tier cap with -c copy instead of
re-encoding them.
- Never upscale: filter the rendition ladder against the source height and
drop the previously unused _target_height.
- Free tier now emits a single rendition (min(source, 720)); the 1080/720/480
ladder stays for Pro.
- Set -threads per encoder so multi-rendition jobs stop oversubscribing
small Spaces, and probe the source with one ffprobe call.

Pipeline overlap:
- Upload HLS segments to S3 while ffmpeg is still encoding (12 concurrent
PUTs), removing the post-encode transfer tail.
- Stream downloads straight to disk instead of buffering the whole file, with
progress reported to Redis.
- Pull the cover frame from an encoded segment instead of re-reading and
re-probing the source.
- Stage progress (download 2-14%, encode 15-90%) so the UI moves immediately.

Reliability:
- Rust /process returns 503 when the queue push fails instead of a 200 with
{'status': 'error'} that the backend treated as success.
- Completion payload reports produced 'variants'; the backend only wires
per-resolution URLs that exist.
- Retries wipe the output dir so stale segments cannot be uploaded.
- Storage init failure writes an error status instead of returning silently.
- Beat task pings the video service every 4 minutes to avoid cold starts.
- RUST_SERVICE_URL timeout raised to 60s for cold starts.

Adds MAX_CONCURRENT_JOBS and UPLOAD_CONCURRENCY knobs.

Files changed (6) hide show
  1. README.md +18 -0
  2. src/main.rs +21 -9
  3. src/models.rs +5 -0
  4. src/storage.rs +159 -43
  5. src/transcoder.rs +691 -394
  6. src/worker.rs +101 -42
README.md CHANGED
@@ -28,3 +28,21 @@ In your Hugging Face Space settings, add the following **Secrets** (AWS S3 — m
28
  | `AWS_CLOUDFRONT_DOMAIN` | `cdn.monteeq.com` |
29
 
30
  Leave `S3_ENDPOINT` unset (or empty) so the service uses native AWS S3.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  | `AWS_CLOUDFRONT_DOMAIN` | `cdn.monteeq.com` |
29
 
30
  Leave `S3_ENDPOINT` unset (or empty) so the service uses native AWS S3.
31
+
32
+ ## Performance knobs
33
+
34
+ | Variable | Default | Purpose |
35
+ |---|---|---|
36
+ | `MAX_CONCURRENT_JOBS` | `min(cpus / 2, RAM GB / 1.5, DISK_IO_LIMIT)` | Worker slots. Override when the host reports throttled/shared CPUs. |
37
+ | `DISK_IO_LIMIT` | `4` | Upper bound used by the automatic slot calculation. |
38
+ | `UPLOAD_CONCURRENCY` | `12` | Parallel S3 segment PUTs. |
39
+
40
+ ## Processing pipeline
41
+
42
+ 1. **Validate** — one `ffprobe` call returns dimensions, duration, audio presence and codecs.
43
+ 2. **Download** — streamed from S3 straight to disk (no full-file buffering), with progress reported to Redis.
44
+ 3. **Plan** — if the source is already H.264/AAC and inside the tier cap it is **remuxed** (`-c copy`) instead of re-encoded. Otherwise the ladder is filtered against the source height, so the service never upscales, and the free tier emits a single rendition.
45
+ 4. **Package** — ffmpeg writes HLS to a temp dir while a background task uploads each segment to S3 as soon as it is complete, so transfer overlaps the encode.
46
+ 5. **Cover** — a frame is pulled from an already-encoded segment (~10% into the video), falling back to the source only if needed, then uploaded to `thumbnails/{task_id}.jpg`.
47
+ 6. **Report** — `task:status:{task_id}` carries progress, and `variants` (the playlist names actually produced) so the backend only advertises renditions that exist.
48
+
src/main.rs CHANGED
@@ -2,6 +2,8 @@ use std::sync::Arc;
2
  use axum::{
3
  routing::{post, get},
4
  extract::{Json, Path, State}, Router,
 
 
5
  };
6
  // use std::net::SocketAddr; // Removed unused import
7
  use tower_http::cors::CorsLayer;
@@ -104,7 +106,7 @@ async fn main() {
104
  async fn process_video(
105
  State(state): State<Arc<AppState>>,
106
  Json(payload): Json<ProcessRequest>
107
- ) -> Json<serde_json::Value> {
108
  let cover_source = if payload.cover_source.trim().is_empty() {
109
  if payload.skip_thumbnail { "custom".to_string() } else { "auto".to_string() }
110
  } else {
@@ -127,6 +129,7 @@ async fn process_video(
127
  message: "Task added to priority queue".to_string(),
128
  cover_url: None,
129
  cover_source: Some(cover_source),
 
130
  };
131
 
132
  // Save status to Redis with 24h TTL
@@ -138,17 +141,25 @@ async fn process_video(
138
  match state.scheduler.push_task(task).await {
139
  Ok(_) => {
140
  println!("[UPLOAD] Task accepted: {}", payload.task_id);
141
- Json(serde_json::json!({
142
- "status": "accepted",
143
- "task_id": payload.task_id
144
- }))
 
 
 
145
  },
146
  Err(e) => {
147
  eprintln!("[ERROR] Failed to push task {}: {}", payload.task_id, e);
148
- Json(serde_json::json!({
149
- "status": "error",
150
- "message": e.to_string()
151
- }))
 
 
 
 
 
152
  }
153
  }
154
  }
@@ -168,6 +179,7 @@ async fn get_status(
168
  message: "Failed to parse status".to_string(),
169
  cover_url: None,
170
  cover_source: None,
 
171
  });
172
  Json(Some(status))
173
  },
 
2
  use axum::{
3
  routing::{post, get},
4
  extract::{Json, Path, State}, Router,
5
+ http::StatusCode,
6
+ response::IntoResponse,
7
  };
8
  // use std::net::SocketAddr; // Removed unused import
9
  use tower_http::cors::CorsLayer;
 
106
  async fn process_video(
107
  State(state): State<Arc<AppState>>,
108
  Json(payload): Json<ProcessRequest>
109
+ ) -> impl IntoResponse {
110
  let cover_source = if payload.cover_source.trim().is_empty() {
111
  if payload.skip_thumbnail { "custom".to_string() } else { "auto".to_string() }
112
  } else {
 
129
  message: "Task added to priority queue".to_string(),
130
  cover_url: None,
131
  cover_source: Some(cover_source),
132
+ variants: None,
133
  };
134
 
135
  // Save status to Redis with 24h TTL
 
141
  match state.scheduler.push_task(task).await {
142
  Ok(_) => {
143
  println!("[UPLOAD] Task accepted: {}", payload.task_id);
144
+ (
145
+ StatusCode::ACCEPTED,
146
+ Json(serde_json::json!({
147
+ "status": "accepted",
148
+ "task_id": payload.task_id
149
+ })),
150
+ )
151
  },
152
  Err(e) => {
153
  eprintln!("[ERROR] Failed to push task {}: {}", payload.task_id, e);
154
+ // 503 so the backend's raise_for_status() retries instead of
155
+ // believing a task that was never queued.
156
+ (
157
+ StatusCode::SERVICE_UNAVAILABLE,
158
+ Json(serde_json::json!({
159
+ "status": "error",
160
+ "message": e.to_string()
161
+ })),
162
+ )
163
  }
164
  }
165
  }
 
179
  message: "Failed to parse status".to_string(),
180
  cover_url: None,
181
  cover_source: None,
182
+ variants: None,
183
  });
184
  Json(Some(status))
185
  },
src/models.rs CHANGED
@@ -38,4 +38,9 @@ pub struct TaskStatus {
38
  pub cover_url: Option<String>,
39
  #[serde(default, skip_serializing_if = "Option::is_none")]
40
  pub cover_source: Option<String>,
 
 
 
 
 
41
  }
 
38
  pub cover_url: Option<String>,
39
  #[serde(default, skip_serializing_if = "Option::is_none")]
40
  pub cover_source: Option<String>,
41
+ /// Variant playlist names actually produced, e.g. ["720p"] or
42
+ /// ["1080p", "720p", "480p"]. The backend wires per-resolution URLs from
43
+ /// this so it never advertises a rendition that was not generated.
44
+ #[serde(default, skip_serializing_if = "Option::is_none")]
45
+ pub variants: Option<Vec<String>>,
46
  }
src/storage.rs CHANGED
@@ -2,8 +2,21 @@ use aws_config::meta::region::RegionProviderChain;
2
  use aws_sdk_s3::Client;
3
  use aws_sdk_s3::primitives::ByteStream;
4
  use anyhow::{Result, anyhow};
5
- use std::path::Path;
6
  use tokio::fs;
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  pub struct StorageManager {
9
  client: Client,
@@ -17,7 +30,7 @@ impl StorageManager {
17
  let region_name = std::env::var("S3_REGION").ok()
18
  .or_else(|| std::env::var("AWS_S3_REGION_NAME").ok())
19
  .or_else(|| std::env::var("AWS_REGION").ok());
20
-
21
  let region_provider = RegionProviderChain::first_try(region_name.map(Region::new))
22
  .or_default_provider()
23
  .or_else(Region::new("eu-west-1"));
@@ -26,9 +39,9 @@ impl StorageManager {
26
  .region(region_provider)
27
  .load()
28
  .await;
29
-
30
  let mut s3_config_builder = aws_sdk_s3::config::Builder::from(&config);
31
-
32
  // Custom endpoint only when non-empty (empty S3_ENDPOINT → native AWS)
33
  if let Ok(endpoint) = std::env::var("S3_ENDPOINT") {
34
  let endpoint = endpoint.trim().to_string();
@@ -46,65 +59,84 @@ impl StorageManager {
46
  let use_accelerate = std::env::var("AWS_S3_USE_ACCELERATE")
47
  .map(|v| v.to_lowercase() == "true")
48
  .unwrap_or(false);
49
-
50
  if use_accelerate {
51
  println!("Rust: Enabling S3 Transfer Acceleration");
52
  s3_config_builder = s3_config_builder.accelerate(true);
53
  }
54
-
55
  let s3_config = s3_config_builder.build();
56
  let client = Client::from_conf(s3_config);
57
-
58
  let bucket = std::env::var("AWS_STORAGE_BUCKET_NAME")
59
  .or_else(|_| std::env::var("S3_BUCKET_NAME"))
60
  .map_err(|_| anyhow!("Storage bucket name not set (AWS_STORAGE_BUCKET_NAME or S3_BUCKET_NAME)"))?;
61
-
62
  Ok(Self { client, bucket })
63
  }
64
 
65
-
66
- /// Recursively upload HLS directory to S3
67
  pub async fn upload_hls_dir(&self, local_dir: &str, s3_prefix: &str) -> Result<()> {
 
68
  let mut entries = fs::read_dir(local_dir).await?;
 
 
69
 
70
  while let Some(entry) = entries.next_entry().await? {
71
  let path = entry.path();
72
- if path.is_file() {
73
- let filename = path.file_name().unwrap().to_str().unwrap();
74
- let key = format!("{}/{}", s3_prefix, filename);
75
- self.upload_file(&path, &key).await?;
 
 
 
 
 
 
 
 
76
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  }
78
- Ok(())
79
  }
80
 
81
  pub async fn upload_file(&self, local_path: &Path, key: &str) -> Result<()> {
82
- let data = fs::read(local_path).await?;
83
- let mime_type = match local_path.extension().and_then(|s| s.to_str()) {
84
- Some("m3u8") => "application/x-mpegURL",
85
- Some("ts") => "video/MP2T",
86
- Some("jpg") | Some("jpeg") => "image/jpeg",
87
- _ => "application/octet-stream",
88
- };
89
-
90
- let body = ByteStream::from(data);
91
-
92
- self.client
93
- .put_object()
94
- .bucket(&self.bucket)
95
- .key(key)
96
- .body(body)
97
- .content_type(mime_type)
98
- .send()
99
- .await
100
- .map_err(|e| anyhow!("Upload failed: {}", e))?;
101
-
102
- Ok(())
103
  }
104
 
105
- pub async fn download_file(&self, key: &str, local_path: &Path) -> Result<()> {
 
 
 
 
 
 
 
 
106
  println!("Attempting to download from S3: bucket={}, key={}", self.bucket, key);
107
- let res = self.client
 
108
  .get_object()
109
  .bucket(&self.bucket)
110
  .key(key)
@@ -112,14 +144,98 @@ impl StorageManager {
112
  .await
113
  .map_err(|e| {
114
  let service_err = e.into_service_error();
115
- anyhow!("S3 Download Error [Bucket: {}, Key: {}]: {}", self.bucket, key, service_err)
 
 
 
 
 
116
  })?;
117
 
118
- let data = res.body.collect().await
119
- .map_err(|e| anyhow!("Failed to collect body: {}", e))?
120
- .into_bytes();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
- fs::write(local_path, data).await?;
123
  Ok(())
124
  }
125
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  use aws_sdk_s3::Client;
3
  use aws_sdk_s3::primitives::ByteStream;
4
  use anyhow::{Result, anyhow};
5
+ use std::path::{Path, PathBuf};
6
  use tokio::fs;
7
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
8
+ use tokio::task::JoinSet;
9
+
10
+ /// How many segment PUTs may be in flight at once.
11
+ /// Sequential uploads were the bulk of the post-encode tail; 12 keeps the
12
+ /// connection pool busy without hammering S3 from a small Space.
13
+ fn upload_concurrency() -> usize {
14
+ std::env::var("UPLOAD_CONCURRENCY")
15
+ .ok()
16
+ .and_then(|v| v.parse::<usize>().ok())
17
+ .filter(|v| *v > 0)
18
+ .unwrap_or(12)
19
+ }
20
 
21
  pub struct StorageManager {
22
  client: Client,
 
30
  let region_name = std::env::var("S3_REGION").ok()
31
  .or_else(|| std::env::var("AWS_S3_REGION_NAME").ok())
32
  .or_else(|| std::env::var("AWS_REGION").ok());
33
+
34
  let region_provider = RegionProviderChain::first_try(region_name.map(Region::new))
35
  .or_default_provider()
36
  .or_else(Region::new("eu-west-1"));
 
39
  .region(region_provider)
40
  .load()
41
  .await;
42
+
43
  let mut s3_config_builder = aws_sdk_s3::config::Builder::from(&config);
44
+
45
  // Custom endpoint only when non-empty (empty S3_ENDPOINT → native AWS)
46
  if let Ok(endpoint) = std::env::var("S3_ENDPOINT") {
47
  let endpoint = endpoint.trim().to_string();
 
59
  let use_accelerate = std::env::var("AWS_S3_USE_ACCELERATE")
60
  .map(|v| v.to_lowercase() == "true")
61
  .unwrap_or(false);
62
+
63
  if use_accelerate {
64
  println!("Rust: Enabling S3 Transfer Acceleration");
65
  s3_config_builder = s3_config_builder.accelerate(true);
66
  }
67
+
68
  let s3_config = s3_config_builder.build();
69
  let client = Client::from_conf(s3_config);
70
+
71
  let bucket = std::env::var("AWS_STORAGE_BUCKET_NAME")
72
  .or_else(|_| std::env::var("S3_BUCKET_NAME"))
73
  .map_err(|_| anyhow!("Storage bucket name not set (AWS_STORAGE_BUCKET_NAME or S3_BUCKET_NAME)"))?;
74
+
75
  Ok(Self { client, bucket })
76
  }
77
 
78
+ /// Upload every file in `local_dir` to `s3_prefix`, several at a time.
79
+ #[allow(dead_code)]
80
  pub async fn upload_hls_dir(&self, local_dir: &str, s3_prefix: &str) -> Result<()> {
81
+ let concurrency = upload_concurrency();
82
  let mut entries = fs::read_dir(local_dir).await?;
83
+ let mut join: JoinSet<Result<()>> = JoinSet::new();
84
+ let mut first_err: Option<anyhow::Error> = None;
85
 
86
  while let Some(entry) = entries.next_entry().await? {
87
  let path = entry.path();
88
+ if !path.is_file() {
89
+ continue;
90
+ }
91
+ let filename = match path.file_name().and_then(|n| n.to_str()) {
92
+ Some(n) => n.to_string(),
93
+ None => continue,
94
+ };
95
+
96
+ while join.len() >= concurrency {
97
+ if let Some(res) = join.join_next().await {
98
+ record(&mut first_err, res);
99
+ }
100
  }
101
+
102
+ let client = self.client.clone();
103
+ let bucket = self.bucket.clone();
104
+ let key = format!("{}/{}", s3_prefix, filename);
105
+ join.spawn(async move { put_file(client, bucket, path, key).await });
106
+ }
107
+
108
+ while let Some(res) = join.join_next().await {
109
+ record(&mut first_err, res);
110
+ }
111
+
112
+ match first_err {
113
+ Some(e) => Err(e),
114
+ None => Ok(()),
115
  }
 
116
  }
117
 
118
  pub async fn upload_file(&self, local_path: &Path, key: &str) -> Result<()> {
119
+ put_file(
120
+ self.client.clone(),
121
+ self.bucket.clone(),
122
+ local_path.to_path_buf(),
123
+ key.to_string(),
124
+ )
125
+ .await
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  }
127
 
128
+ /// Stream an S3 object to disk instead of buffering the whole file in RAM.
129
+ /// `progress` receives `(bytes_written, total_bytes)`; total is 0 when the
130
+ /// server did not report a Content-Length.
131
+ pub async fn download_file(
132
+ &self,
133
+ key: &str,
134
+ local_path: &Path,
135
+ progress: Option<tokio::sync::mpsc::UnboundedSender<(u64, u64)>>,
136
+ ) -> Result<()> {
137
  println!("Attempting to download from S3: bucket={}, key={}", self.bucket, key);
138
+ let res = self
139
+ .client
140
  .get_object()
141
  .bucket(&self.bucket)
142
  .key(key)
 
144
  .await
145
  .map_err(|e| {
146
  let service_err = e.into_service_error();
147
+ anyhow!(
148
+ "S3 Download Error [Bucket: {}, Key: {}]: {}",
149
+ self.bucket,
150
+ key,
151
+ service_err
152
+ )
153
  })?;
154
 
155
+ let total = res.content_length().unwrap_or(0) as u64;
156
+ let mut reader = res.body.into_async_read();
157
+ let mut file = fs::File::create(local_path).await?;
158
+
159
+ let mut buf = vec![0u8; 256 * 1024];
160
+ let mut written: u64 = 0;
161
+ let mut last_report = 0u64;
162
+
163
+ loop {
164
+ let n = reader.read(&mut buf).await?;
165
+ if n == 0 {
166
+ break;
167
+ }
168
+ file.write_all(&buf[..n]).await?;
169
+ written += n as u64;
170
+
171
+ if let Some(tx) = progress.as_ref() {
172
+ // Report at most ~every 4 MiB to keep Redis writes cheap.
173
+ if written - last_report >= 4 * 1024 * 1024 {
174
+ last_report = written;
175
+ let _ = tx.send((written, total));
176
+ }
177
+ }
178
+ }
179
+
180
+ file.flush().await?;
181
+ if let Some(tx) = progress.as_ref() {
182
+ let _ = tx.send((written, total.max(written)));
183
+ }
184
 
 
185
  Ok(())
186
  }
187
  }
188
+
189
+ fn record(first_err: &mut Option<anyhow::Error>, res: Result<Result<()>, tokio::task::JoinError>) {
190
+ match res {
191
+ Ok(Ok(())) => {}
192
+ Ok(Err(e)) => {
193
+ if first_err.is_none() {
194
+ *first_err = Some(e);
195
+ }
196
+ }
197
+ Err(e) => {
198
+ if first_err.is_none() {
199
+ *first_err = Some(anyhow!("upload task failed: {}", e));
200
+ }
201
+ }
202
+ }
203
+ }
204
+
205
+ async fn put_file(client: Client, bucket: String, path: PathBuf, key: String) -> Result<()> {
206
+ let mime_type = match path.extension().and_then(|s| s.to_str()) {
207
+ Some("m3u8") => "application/x-mpegURL",
208
+ Some("ts") => "video/MP2T",
209
+ Some("m4s") => "video/iso.segment",
210
+ Some("mp4") => "video/mp4",
211
+ Some("jpg") | Some("jpeg") => "image/jpeg",
212
+ _ => "application/octet-stream",
213
+ };
214
+
215
+ // Streamed from disk — no full-file read into memory.
216
+ let body = ByteStream::from_path(&path)
217
+ .await
218
+ .map_err(|e| anyhow!("Failed to open {} for upload: {}", path.display(), e))?;
219
+
220
+ client
221
+ .put_object()
222
+ .bucket(bucket)
223
+ .key(&key)
224
+ .body(body)
225
+ .content_type(mime_type)
226
+ .send()
227
+ .await
228
+ .map_err(|e| anyhow!("Upload failed for {}: {}", key, e))?;
229
+
230
+ Ok(())
231
+ }
232
+
233
+ /// Cheap clone so callers can share one manager across spawned tasks.
234
+ impl Clone for StorageManager {
235
+ fn clone(&self) -> Self {
236
+ Self {
237
+ client: self.client.clone(),
238
+ bucket: self.bucket.clone(),
239
+ }
240
+ }
241
+ }
src/transcoder.rs CHANGED
@@ -2,10 +2,14 @@ use tokio::process::Command;
2
  use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
3
  use fred::interfaces::KeysInterface;
4
  use anyhow::{Result, anyhow};
 
5
  use std::path::Path;
6
  use std::process::Stdio;
 
 
7
  use std::time::{Duration, Instant};
8
  use tokio::fs;
 
9
  use crate::storage::StorageManager;
10
  use crate::models::{UserTier, TaskStatus};
11
  use crate::queue::WeightedScheduler;
@@ -14,10 +18,14 @@ use crate::queue::WeightedScheduler;
14
  const JOB_PROGRESS_TTL_SECS: i64 = 300;
15
  /// Minimum gap between progress Redis writes.
16
  const PROGRESS_REPORT_INTERVAL: Duration = Duration::from_secs(1);
 
 
 
 
 
17
 
18
  pub struct TranscodingConfig {
19
  pub preset: String,
20
- pub max_height: i32,
21
  pub crf: String,
22
  }
23
 
@@ -26,18 +34,25 @@ impl TranscodingConfig {
26
  match tier {
27
  UserTier::Free => Self {
28
  preset: "ultrafast".to_string(),
29
- max_height: 720,
30
  crf: "26".to_string(), // Slightly lower quality for space/speed
31
  },
32
  UserTier::Pro => Self {
33
  preset: "medium".to_string(),
34
- max_height: 2160, // Support up to 4K
35
  crf: "23".to_string(), // Better quality
36
  },
37
  }
38
  }
39
  }
40
 
 
 
 
 
 
 
 
 
 
41
  fn job_progress_key(job_id: &str) -> String {
42
  format!("job:progress:{}", job_id)
43
  }
@@ -67,6 +82,143 @@ pub async fn clear_job_progress(sched: &WeightedScheduler, job_id: &str) {
67
  .unwrap_or_default();
68
  }
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  pub async fn process(
71
  _video_id: String, // Platform ID
72
  video_path: &str, // Local filesystem path
@@ -74,9 +226,13 @@ pub async fn process(
74
  tier: UserTier,
75
  skip_thumbnail: bool,
76
  scheduler: Option<WeightedScheduler>,
77
- task_id: String, // Processing Key (= job_id for progress Redis key)
78
- ) -> Result<()> {
79
- println!("Starting processing for task_id={} video_path={}", task_id, video_path);
 
 
 
 
80
 
81
  // Check if file exists
82
  if !Path::new(video_path).exists() {
@@ -85,31 +241,16 @@ pub async fn process(
85
 
86
  let config = TranscodingConfig::for_tier(&tier);
87
 
88
- // 1. Metadata extraction
89
- if let Some(ref sched) = scheduler {
90
- let status = TaskStatus {
91
- progress: 5,
92
- status: "processing".to_string(),
93
- message: "Analyzing video streams and metadata...".to_string(),
94
- cover_url: None,
95
- cover_source: None,
96
- };
97
- let status_json = serde_json::to_string(&status).unwrap();
98
- let _: () = sched
99
- .client()
100
- .set(
101
- format!("task:status:{}", task_id),
102
- status_json,
103
- Some(fred::types::Expiration::EX(86400)),
104
- None,
105
- false,
106
- )
107
- .await
108
- .unwrap_or_default();
109
- }
110
- println!("Extracting metadata for {}", video_path);
111
- let (width, height, has_audio, duration_secs) = match get_video_metadata(video_path).await {
112
- Ok(m) => m,
113
  Err(e) => {
114
  eprintln!("Metadata extraction failed for {}: {}", video_path, e);
115
  if let Some(ref sched) = scheduler {
@@ -118,10 +259,15 @@ pub async fn process(
118
  return Err(e);
119
  }
120
  };
121
- let aspect_ratio = width / height;
122
  println!(
123
- "Metadata: width={} height={} has_audio={} duration={:.3}s aspect_ratio={}",
124
- width, height, has_audio, duration_secs, aspect_ratio
 
 
 
 
 
125
  );
126
 
127
  // ── Orientation validation ────────────────────────────────────────────────
@@ -129,7 +275,7 @@ pub async fn process(
129
  // dimensions. Square-ish videos (aspect 0.9–1.1) always pass regardless of
130
  // declared type. This catches client-side bypasses (devtools, direct API).
131
  {
132
- let ratio = width as f64 / height as f64;
133
  let is_squareish = ratio >= 0.9 && ratio <= 1.1;
134
  if !is_squareish {
135
  let mismatch = match format {
@@ -141,8 +287,8 @@ pub async fn process(
141
  let msg = format!(
142
  "Video orientation doesn't match the selected format: \
143
  video is {}x{} ({} {}) but format is \"{}\"",
144
- width,
145
- height,
146
  if ratio > 1.1 { "landscape" } else { "portrait" },
147
  ratio,
148
  format,
@@ -156,393 +302,240 @@ pub async fn process(
156
  }
157
  }
158
 
159
- // 2. Prep Output
 
160
  let output_dir = format!("{}_hls", video_path);
161
- if !Path::new(&output_dir).exists() {
162
- fs::create_dir_all(&output_dir).await?;
163
  }
 
164
 
165
- // 3. Transcode + Thumbnail Concurrently
166
- let transcoding_fut = transcode_tiered(
167
- video_path,
168
- &output_dir,
169
- format,
170
- &config,
171
- scheduler.clone(),
172
- task_id.clone(),
173
- has_audio,
174
- &tier,
175
- duration_secs,
176
  );
177
- let v_path = video_path.to_string();
178
- let thumbnail_fut = async move {
179
- if !skip_thumbnail {
180
- generate_thumbnail(&v_path).await
181
- } else {
182
- Ok(())
183
- }
184
- };
185
 
186
- // Run both. Pro users might benefit from faster total completion time
187
- let (trans_res, thumb_res) = tokio::join!(transcoding_fut, thumbnail_fut);
 
188
 
189
- match (&trans_res, &thumb_res) {
190
- (Ok(()), Ok(())) => {}
191
- _ => {
192
- if let Some(ref sched) = scheduler {
193
- clear_job_progress(sched, &task_id).await;
194
- }
195
- trans_res?;
196
- thumb_res?;
197
- }
198
- }
199
-
200
- // 4. Upload to Storage
201
- match StorageManager::new().await {
202
- Ok(storage) => {
203
- let s3_prefix = format!("videos/{}", task_id);
204
- if let Some(ref sched) = scheduler {
205
- let status = TaskStatus {
206
- progress: 90,
207
- status: "processing".to_string(),
208
- message: "Syncing video segments to edge nodes...".to_string(),
209
- cover_url: None,
210
- cover_source: None,
211
- };
212
- let status_json = serde_json::to_string(&status).unwrap();
213
- let _: () = sched
214
- .client()
215
- .set(
216
- format!("task:status:{}", task_id),
217
- status_json,
218
- Some(fred::types::Expiration::EX(86400)),
219
- None,
220
- false,
221
- )
222
- .await
223
- .unwrap_or_default();
224
- }
225
- storage.upload_hls_dir(&output_dir, &s3_prefix).await?;
226
-
227
- // Upload thumbnail too
228
- if !skip_thumbnail {
229
- let thumb_path = format!("{}.jpg", video_path);
230
- let thumb_key = format!("thumbnails/{}.jpg", task_id);
231
- storage.upload_file(Path::new(&thumb_path), &thumb_key).await?;
232
- }
233
- }
234
- Err(e) => {
235
- eprintln!("Storage Manager initialization failed: {}. Skipping upload.", e);
236
- if let Some(ref sched) = scheduler {
237
- clear_job_progress(sched, &task_id).await;
238
- }
239
- return Err(anyhow!("Storage initialization failed: {}", e));
240
  }
 
241
  }
242
- Ok(())
243
- }
244
-
245
- /// Pick the first width/height pair from `ffprobe -of json -show_entries stream=width,height`.
246
- ///
247
- /// JSON is used instead of `-of csv=s=x:p=0` because the CSV writer can emit
248
- /// extra sections/fields depending on the container (e.g. QuickTime timecode
249
- /// tracks and MPEG-TS programs produce multiple lines, and some files end with
250
- /// a bare separator like `1080x1080x`). Splitting the whole stdout on 'x' then
251
- /// rejects perfectly valid values.
252
- fn parse_dimensions(stdout: &[u8]) -> Result<(i32, i32)> {
253
- let raw = String::from_utf8_lossy(stdout);
254
- let json: serde_json::Value = serde_json::from_str(&raw)
255
- .map_err(|e| anyhow!("Invalid ffprobe JSON ({}): {}", e, raw.trim()))?;
256
-
257
- let streams = json
258
- .get("streams")
259
- .and_then(|v| v.as_array())
260
- .ok_or_else(|| anyhow!("ffprobe returned no streams: {}", raw.trim()))?;
261
 
262
- for stream in streams {
263
- let width = stream.get("width").and_then(|v| v.as_i64());
264
- let height = stream.get("height").and_then(|v| v.as_i64());
265
- if let (Some(w), Some(h)) = (width, height) {
266
- if w > 0 && h > 0 {
267
- return Ok((w as i32, h as i32));
268
- }
269
  }
270
  }
271
 
272
- Err(anyhow!(
273
- "ffprobe returned no usable width/height: {}",
274
- raw.trim()
275
- ))
276
- }
277
-
278
- /// Probe width/height, audio presence, and total duration (seconds).
279
- /// Duration comes from format context (`format=duration`), with stream duration as fallback —
280
- /// equivalent to reading container duration / stream time_base×duration in ffmpeg-next.
281
- async fn get_video_metadata(video_path: &str) -> Result<(i32, i32, bool, f64)> {
282
- let output = Command::new("ffprobe")
283
- .args([
284
- "-v",
285
- "error",
286
- "-select_streams",
287
- "v:0",
288
- "-show_entries",
289
- "stream=width,height",
290
- "-of",
291
- "json",
292
- video_path,
293
- ])
294
- .output()
295
- .await?;
296
-
297
- if !output.status.success() {
298
- return Err(anyhow!(
299
- "ffprobe failed for {}: {}",
300
- video_path,
301
- String::from_utf8_lossy(&output.stderr).trim()
302
- ));
303
- }
304
-
305
- let (width, height) = parse_dimensions(&output.stdout)?;
306
-
307
- // Check for audio
308
- let audio_output = Command::new("ffprobe")
309
- .args(&[
310
- "-v",
311
- "error",
312
- "-select_streams",
313
- "a",
314
- "-show_entries",
315
- "stream=index",
316
- "-of",
317
- "csv=p=0",
318
- video_path,
319
- ])
320
- .output()
321
- .await?;
322
-
323
- let has_audio = !String::from_utf8(audio_output.stdout)?.trim().is_empty();
324
-
325
- let duration_secs = get_video_duration_secs(video_path).await.unwrap_or(0.0);
326
-
327
- Ok((width, height, has_audio, duration_secs))
328
  }
329
 
330
- async fn get_video_duration_secs(video_path: &str) -> Result<f64> {
331
- // Prefer container / format duration (same source as AVFormatContext.duration).
332
- let format_out = Command::new("ffprobe")
333
- .args(&[
334
- "-v",
335
- "error",
336
- "-show_entries",
337
- "format=duration",
338
- "-of",
339
- "default=noprint_wrappers=1:nokey=1",
340
- video_path,
341
- ])
342
- .output()
343
- .await?;
344
-
345
- let format_s = String::from_utf8_lossy(&format_out.stdout).trim().to_string();
346
- if let Ok(d) = format_s.parse::<f64>() {
347
- if d.is_finite() && d > 0.0 {
348
- return Ok(d);
349
- }
350
- }
351
-
352
- // Fallback: stream duration (seconds) — akin to stream.duration * av_q2d(time_base).
353
- let stream_out = Command::new("ffprobe")
354
- .args(&[
355
- "-v",
356
- "error",
357
- "-select_streams",
358
- "v:0",
359
- "-show_entries",
360
- "stream=duration",
361
- "-of",
362
- "default=noprint_wrappers=1:nokey=1",
363
- video_path,
364
- ])
365
- .output()
366
- .await?;
367
-
368
- let stream_s = String::from_utf8_lossy(&stream_out.stdout).trim().to_string();
369
- let d: f64 = stream_s
370
- .parse()
371
- .map_err(|_| anyhow!("Invalid duration from ffprobe: format={:?} stream={:?}", format_s, stream_s))?;
372
- if !d.is_finite() || d <= 0.0 {
373
- return Err(anyhow!("Non-positive duration: {}", d));
374
  }
375
- Ok(d)
376
  }
377
 
378
- async fn transcode_tiered(
 
379
  input: &str,
380
  output_dir: &str,
381
- format: &str,
 
 
382
  config: &TranscodingConfig,
383
- scheduler: Option<WeightedScheduler>,
384
- task_id: String,
385
- has_audio: bool,
386
- tier: &UserTier,
387
- duration_secs: f64,
388
- ) -> Result<()> {
389
- println!("Transcoding tiered levels for {} -> {}", input, output_dir);
390
-
391
- let source_height = get_video_height(input).await?;
392
- let _target_height = source_height.min(config.max_height);
393
-
394
- // ── 1. Determine variants ────────────────────────────────────────────────
395
- // num_variants = how many video streams (and therefore audio streams) we produce.
396
- // stream_map uses unique a:N per variant — sharing a:0 across variants is the
397
- // root cause of FFmpeg error "Same elementary stream found more than once".
398
- let (filter, stream_map, num_variants): (String, String, usize) = if format == "flash" {
399
- // Single quality for flash (Original resolution)
400
- let sm = if has_audio {
401
- "v:0,a:0,name:original".to_string()
402
- } else {
403
- "v:0,name:original".to_string()
404
- };
405
- (format!("[0:v]scale=w=-2:h={}[vout]", source_height), sm, 1)
406
- } else if config.max_height <= 720 {
407
- // Free tier — two quality levels, capped at 720p
408
- let sm = if has_audio {
409
- "v:0,a:0,name:720p v:1,a:1,name:480p".to_string() // ← unique a:0 / a:1
410
- } else {
411
- "v:0,name:720p v:1,name:480p".to_string()
412
- };
413
- (
414
- "[0:v]split=2[v1][v2]; [v1]scale=w=-2:h=720[v1out]; [v2]scale=w=-2:h=480[v2out]".to_string(),
415
- sm,
416
- 2,
417
- )
418
- } else {
419
- // Pro tier — three quality levels up to 1080p
420
- let sm = if has_audio {
421
- "v:0,a:0,name:1080p v:1,a:1,name:720p v:2,a:2,name:480p".to_string() // ← unique a:0/a:1/a:2
422
- } else {
423
- "v:0,name:1080p v:1,name:720p v:2,name:480p".to_string()
424
- };
425
- (
426
- "[0:v]split=3[v1][v2][v3]; [v1]scale=w=-2:h=1080[v1out]; [v2]scale=w=-2:h=720[v2out]; [v3]scale=w=-2:h=480[v3out]".to_string(),
427
- sm,
428
- 3,
429
- )
430
- };
431
 
432
- // ── 2. Build args as Vec<String> so we can push dynamic per-stream options ─
433
- let mut args: Vec<String> = vec![
434
- "-i".into(),
435
- input.into(),
436
- // NOTE: Do NOT add global -c:a here — it conflicts with per-stream -c:a:N below
437
- "-preset".into(),
438
- config.preset.clone(),
439
- "-crf".into(),
440
- config.crf.clone(),
441
  "-f".into(),
442
  "hls".into(),
443
  "-hls_time".into(),
444
- "6".into(),
445
  "-hls_playlist_type".into(),
446
  "vod".into(),
447
  "-master_pl_name".into(),
448
  "master.m3u8".into(),
449
- "-filter_complex".into(),
450
- filter.clone(),
451
- ];
452
 
453
- // ── 3. Video stream mappings ─────────────────────────────────────────────
454
- if filter.contains("split=3") {
455
- args.extend(
456
- [
457
- "-map", "[v1out]", "-c:v:0", "libx264", "-b:v:0", "5000k", "-map", "[v2out]",
458
- "-c:v:1", "libx264", "-b:v:1", "2800k", "-map", "[v3out]", "-c:v:2", "libx264",
459
- "-b:v:2", "1200k",
460
- ]
461
- .iter()
462
- .map(|s| s.to_string()),
463
- );
464
- } else if filter.contains("split=2") {
465
- args.extend(
466
- [
467
- "-map", "[v1out]", "-c:v:0", "libx264", "-b:v:0", "2800k", "-map", "[v2out]",
468
- "-c:v:1", "libx264", "-b:v:1", "1200k",
469
- ]
470
- .iter()
471
- .map(|s| s.to_string()),
472
- );
 
 
 
473
  } else {
474
- args.extend(
475
- ["-map", "[vout]", "-c:v:0", "libx264", "-b:v:0", "2800k"]
476
- .iter()
477
- .map(|s| s.to_string()),
478
- );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
479
  }
480
 
481
- // ── 4. Audio stream mappings ─────────────────────────────────────────────
482
- // Each HLS variant needs its OWN audio output stream. We map the single
483
- // source audio track N times (once per variant) so the muxer can write
484
- // independent AAC streams into the separate .ts segment files.
485
- if has_audio {
486
- for _ in 0..num_variants {
487
  args.push("-map".into());
488
- args.push("0:a?".into());
489
  }
490
- for i in 0..num_variants {
491
- args.push(format!("-c:a:{}", i));
492
- args.push("aac".into());
493
- args.push(format!("-b:a:{}", i));
494
- args.push("128k".into());
 
 
495
  }
496
  }
497
 
498
- // ── 5. HLS output options ────────────────────────────────────────────────
499
- let segment_filename = format!("{}/%v_%03d.ts", output_dir);
500
- let output_pattern = format!("{}/%v.m3u8", output_dir);
 
 
 
 
 
 
 
 
 
 
 
 
 
501
 
502
  args.extend([
503
  "-hls_segment_filename".to_string(),
504
- segment_filename,
505
  "-var_stream_map".to_string(),
506
  stream_map,
507
- output_pattern,
508
  ]);
509
 
510
- if let Some(ref sched) = scheduler {
511
- let status = TaskStatus {
512
- progress: 15,
513
- status: "processing".to_string(),
514
- message: format!("Compressing and optimizing video (Tier: {:?})", tier),
515
- cover_url: None,
516
- cover_source: None,
517
- };
518
- let status_json = serde_json::to_string(&status).unwrap();
519
- let _: () = sched
520
- .client()
521
- .set(
522
- format!("task:status:{}", task_id),
523
- status_json,
524
- Some(fred::types::Expiration::EX(86400)),
525
- None,
526
- false,
527
- )
528
- .await
529
- .unwrap_or_default();
530
- set_job_progress(sched, &task_id, 0).await;
531
- }
532
-
533
- run_ffmpeg_with_progress(&args, duration_secs, scheduler.as_ref(), &task_id).await
534
  }
535
 
536
- /// Spawn ffmpeg with `-progress pipe:1`, map `out_time` → percent of input duration,
537
- /// and throttle Redis writes to ~1/sec on `job:progress:{job_id}`.
538
- ///
539
- /// This is the CLI equivalent of walking PTS in an ffmpeg-next encode loop:
540
- /// `progress = (pts * time_base / total_duration) * 100`.
541
  async fn run_ffmpeg_with_progress(
542
  args: &[String],
543
  duration_secs: f64,
544
  scheduler: Option<&WeightedScheduler>,
545
  task_id: &str,
 
 
546
  ) -> Result<()> {
547
  // Machine-readable progress on stdout; keep stderr for errors (drained so the pipe never blocks).
548
  let mut full_args: Vec<String> = vec![
@@ -596,9 +589,9 @@ async fn run_ffmpeg_with_progress(
596
  if force || last_report.elapsed() >= PROGRESS_REPORT_INTERVAL {
597
  if duration_secs > 0.0 {
598
  let current_time_seconds = current_out_us as f64 / 1_000_000.0;
599
- // Cap at 99 until process exit confirms success (then we set 100).
600
- let progress_percent =
601
- ((current_time_seconds / duration_secs) * 100.0).clamp(0.0, 99.0) as u32;
602
  if let Some(sched) = scheduler {
603
  set_job_progress(sched, task_id, progress_percent).await;
604
  }
@@ -619,24 +612,134 @@ async fn run_ffmpeg_with_progress(
619
  return Err(anyhow!("FFmpeg failed: {}", err_text));
620
  }
621
 
622
- if let Some(sched) = scheduler {
623
- set_job_progress(sched, task_id, 100).await;
624
- }
625
  Ok(())
626
  }
627
 
628
- async fn get_video_height(input: &str) -> Result<i32> {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
629
  let output = Command::new("ffprobe")
630
  .args([
631
  "-v",
632
  "error",
633
- "-select_streams",
634
- "v:0",
635
  "-show_entries",
636
- "stream=width,height",
637
  "-of",
638
  "json",
639
- input,
640
  ])
641
  .output()
642
  .await?;
@@ -644,12 +747,110 @@ async fn get_video_height(input: &str) -> Result<i32> {
644
  if !output.status.success() {
645
  return Err(anyhow!(
646
  "ffprobe failed for {}: {}",
647
- input,
648
  String::from_utf8_lossy(&output.stderr).trim()
649
  ));
650
  }
651
 
652
- parse_dimensions(&output.stdout).map(|(_, height)| height)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
653
  }
654
 
655
  async fn generate_thumbnail(video_path: &str) -> Result<()> {
@@ -659,13 +860,12 @@ async fn generate_thumbnail(video_path: &str) -> Result<()> {
659
  }
660
 
661
  /// Seek ~`pct` into the video (default 10%) and write a single JPEG frame.
662
- /// Uses the system ffmpeg CLI (same stack as the rest of this service; equivalent
663
- /// to grabbing a decoded frame via ffmpeg-next around that timestamp).
664
  pub async fn extract_cover_frame(video_path: &str, out_jpg: &str, pct: f64) -> Result<()> {
665
- let duration = match get_video_metadata(video_path).await {
666
- Ok((_, _, _, d)) if d.is_finite() && d > 0.0 => d,
667
- _ => 0.0,
668
- };
 
669
  let seek_secs = if duration > 0.5 {
670
  (duration * pct).clamp(0.0, (duration - 0.05).max(0.0))
671
  } else {
@@ -709,14 +909,20 @@ pub async fn extract_cover_frame(video_path: &str, out_jpg: &str, pct: f64) -> R
709
  }
710
 
711
  /// Auto cover: frame at ~10% duration → JPEG → S3 `thumbnails/{task_id}.jpg`.
 
 
 
712
  /// Returns the S3 key for inclusion in the Redis completion payload.
713
  pub async fn generate_and_upload_auto_cover(
714
  video_path: &str,
 
715
  task_id: &str,
716
  storage: &StorageManager,
717
  ) -> Result<String> {
718
  let cover_local = format!("{}_cover.jpg", video_path);
719
- extract_cover_frame(video_path, &cover_local, 0.1).await?;
 
 
720
 
721
  let cover_key = format!("thumbnails/{}.jpg", task_id);
722
  storage
@@ -730,9 +936,63 @@ pub async fn generate_and_upload_auto_cover(
730
  Ok(cover_key)
731
  }
732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
733
  #[cfg(test)]
734
  mod tests {
735
- use super::parse_dimensions;
 
 
 
 
 
 
 
 
 
 
 
736
 
737
  #[test]
738
  fn picks_first_stream_with_dimensions() {
@@ -760,4 +1020,41 @@ mod tests {
760
  fn rejects_non_json_output() {
761
  assert!(parse_dimensions(b"1080x1080x").is_err());
762
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
763
  }
 
2
  use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
3
  use fred::interfaces::KeysInterface;
4
  use anyhow::{Result, anyhow};
5
+ use std::collections::{HashMap, HashSet};
6
  use std::path::Path;
7
  use std::process::Stdio;
8
+ use std::sync::Arc;
9
+ use std::sync::atomic::{AtomicBool, Ordering};
10
  use std::time::{Duration, Instant};
11
  use tokio::fs;
12
+ use tokio::task::JoinSet;
13
  use crate::storage::StorageManager;
14
  use crate::models::{UserTier, TaskStatus};
15
  use crate::queue::WeightedScheduler;
 
18
  const JOB_PROGRESS_TTL_SECS: i64 = 300;
19
  /// Minimum gap between progress Redis writes.
20
  const PROGRESS_REPORT_INTERVAL: Duration = Duration::from_secs(1);
21
+ /// Target HLS segment length.
22
+ const HLS_SEGMENT_SECS: u32 = 6;
23
+ /// Progress band: encode starts at 15% and may not exceed this.
24
+ const ENCODE_BASE_PCT: u32 = 15;
25
+ const ENCODE_SPAN_PCT: u32 = 75;
26
 
27
  pub struct TranscodingConfig {
28
  pub preset: String,
 
29
  pub crf: String,
30
  }
31
 
 
34
  match tier {
35
  UserTier::Free => Self {
36
  preset: "ultrafast".to_string(),
 
37
  crf: "26".to_string(), // Slightly lower quality for space/speed
38
  },
39
  UserTier::Pro => Self {
40
  preset: "medium".to_string(),
 
41
  crf: "23".to_string(), // Better quality
42
  },
43
  }
44
  }
45
  }
46
 
47
+ /// Highest rendition we consider a "passthrough" candidate per tier. A source
48
+ /// that already fits the cap and is H.264/AAC does not need re-encoding at all.
49
+ fn passthrough_cap(tier: &UserTier) -> i32 {
50
+ match tier {
51
+ UserTier::Free => 720,
52
+ UserTier::Pro => 1080,
53
+ }
54
+ }
55
+
56
  fn job_progress_key(job_id: &str) -> String {
57
  format!("job:progress:{}", job_id)
58
  }
 
82
  .unwrap_or_default();
83
  }
84
 
85
+ /// Everything one ffprobe invocation can tell us about the source.
86
+ #[derive(Debug, Clone)]
87
+ struct Probe {
88
+ width: i32,
89
+ height: i32,
90
+ has_audio: bool,
91
+ duration: f64,
92
+ video_codec: String,
93
+ audio_codec: Option<String>,
94
+ }
95
+
96
+ impl Probe {
97
+ /// True when the video/audio streams can be copied into HLS untouched.
98
+ fn copy_safe(&self) -> bool {
99
+ self.video_codec.eq_ignore_ascii_case("h264")
100
+ && self
101
+ .audio_codec
102
+ .as_deref()
103
+ .map(|c| c.eq_ignore_ascii_case("aac"))
104
+ .unwrap_or(true)
105
+ }
106
+ }
107
+
108
+ /// One output rendition.
109
+ #[derive(Debug, Clone)]
110
+ struct Variant {
111
+ name: String,
112
+ height: i32,
113
+ bitrate: &'static str,
114
+ }
115
+
116
+ fn bitrate_for(height: i32) -> &'static str {
117
+ if height >= 1080 {
118
+ "5000k"
119
+ } else if height >= 720 {
120
+ "2800k"
121
+ } else {
122
+ "1200k"
123
+ }
124
+ }
125
+
126
+ fn label_for(height: i32) -> &'static str {
127
+ if height >= 1080 {
128
+ "1080p"
129
+ } else if height >= 720 {
130
+ "720p"
131
+ } else {
132
+ "480p"
133
+ }
134
+ }
135
+
136
+ /// Decide the rendition set.
137
+ ///
138
+ /// Rules, in priority order:
139
+ /// 1. Source already H.264/AAC and inside the tier cap → single passthrough
140
+ /// variant at native resolution (no encode at all).
141
+ /// 2. Flash → single variant at native resolution ("original").
142
+ /// 3. Otherwise → ladder capped by tier, filtered against the source so we
143
+ /// never upscale. Free tier produces a single rendition; Pro keeps the
144
+ /// 1080/720/480 ladder.
145
+ fn plan_variants(format: &str, tier: &UserTier, probe: &Probe) -> (Vec<Variant>, bool) {
146
+ let cap = passthrough_cap(tier);
147
+
148
+ if probe.copy_safe() && probe.height <= cap {
149
+ let name = if format == "flash" {
150
+ "original".to_string()
151
+ } else {
152
+ label_for(probe.height).to_string()
153
+ };
154
+ return (
155
+ vec![Variant {
156
+ name,
157
+ height: probe.height,
158
+ bitrate: bitrate_for(probe.height),
159
+ }],
160
+ true,
161
+ );
162
+ }
163
+
164
+ if format == "flash" {
165
+ return (
166
+ vec![Variant {
167
+ name: "original".to_string(),
168
+ height: probe.height,
169
+ bitrate: bitrate_for(probe.height),
170
+ }],
171
+ false,
172
+ );
173
+ }
174
+
175
+ let top = match tier {
176
+ UserTier::Pro => 1080,
177
+ UserTier::Free => 720,
178
+ };
179
+
180
+ // Free tier: one rendition at the source height, capped. Encoding the whole
181
+ // ladder is what made 2-vCPU Spaces crawl.
182
+ if matches!(tier, UserTier::Free) {
183
+ let h = probe.height.min(top).max(2);
184
+ return (
185
+ vec![Variant {
186
+ name: label_for(h).to_string(),
187
+ height: h,
188
+ bitrate: bitrate_for(h),
189
+ }],
190
+ false,
191
+ );
192
+ }
193
+
194
+ let mut variants: Vec<Variant> = Vec::new();
195
+ for h in [1080, 720, 480] {
196
+ if h <= top && probe.height >= h {
197
+ variants.push(Variant {
198
+ name: format!("{}p", h),
199
+ height: h,
200
+ bitrate: bitrate_for(h),
201
+ });
202
+ }
203
+ }
204
+
205
+ // Source smaller than every ladder step: keep one rendition at the source
206
+ // height (never upscale) and name it after the bucket it falls into.
207
+ if variants.is_empty() {
208
+ let h = probe.height.min(top).max(2);
209
+ variants.push(Variant {
210
+ name: label_for(h).to_string(),
211
+ height: h,
212
+ bitrate: bitrate_for(h),
213
+ });
214
+ }
215
+
216
+ (variants, false)
217
+ }
218
+
219
+ /// Encode (or remux) into HLS, uploading segments while ffmpeg is still running,
220
+ /// then generate the cover. Returns the output directory.
221
+ #[allow(clippy::too_many_arguments)]
222
  pub async fn process(
223
  _video_id: String, // Platform ID
224
  video_path: &str, // Local filesystem path
 
226
  tier: UserTier,
227
  skip_thumbnail: bool,
228
  scheduler: Option<WeightedScheduler>,
229
+ task_id: String,
230
+ storage: Arc<StorageManager>,
231
+ ) -> Result<(String, Vec<String>)> {
232
+ println!(
233
+ "Starting processing for task_id={} video_path={}",
234
+ task_id, video_path
235
+ );
236
 
237
  // Check if file exists
238
  if !Path::new(video_path).exists() {
 
241
 
242
  let config = TranscodingConfig::for_tier(&tier);
243
 
244
+ status(
245
+ scheduler.as_ref(),
246
+ &task_id,
247
+ 5,
248
+ "Analyzing video streams and metadata...",
249
+ )
250
+ .await;
251
+
252
+ let probe = match probe_video(video_path).await {
253
+ Ok(p) => p,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  Err(e) => {
255
  eprintln!("Metadata extraction failed for {}: {}", video_path, e);
256
  if let Some(ref sched) = scheduler {
 
259
  return Err(e);
260
  }
261
  };
262
+
263
  println!(
264
+ "Metadata: width={} height={} has_audio={} duration={:.3}s codec={} audio={:?}",
265
+ probe.width,
266
+ probe.height,
267
+ probe.has_audio,
268
+ probe.duration,
269
+ probe.video_codec,
270
+ probe.audio_codec
271
  );
272
 
273
  // ── Orientation validation ────────────────────────────────────────────────
 
275
  // dimensions. Square-ish videos (aspect 0.9–1.1) always pass regardless of
276
  // declared type. This catches client-side bypasses (devtools, direct API).
277
  {
278
+ let ratio = probe.width as f64 / probe.height as f64;
279
  let is_squareish = ratio >= 0.9 && ratio <= 1.1;
280
  if !is_squareish {
281
  let mismatch = match format {
 
287
  let msg = format!(
288
  "Video orientation doesn't match the selected format: \
289
  video is {}x{} ({} {}) but format is \"{}\"",
290
+ probe.width,
291
+ probe.height,
292
  if ratio > 1.1 { "landscape" } else { "portrait" },
293
  ratio,
294
  format,
 
302
  }
303
  }
304
 
305
+ // 2. Prep Output — wipe leftovers from a previous attempt so a retry can
306
+ // never upload stale segments alongside fresh ones.
307
  let output_dir = format!("{}_hls", video_path);
308
+ if Path::new(&output_dir).exists() {
309
+ fs::remove_dir_all(&output_dir).await.ok();
310
  }
311
+ fs::create_dir_all(&output_dir).await?;
312
 
313
+ let (variants, copy) = plan_variants(format, &tier, &probe);
314
+ let variant_names: Vec<String> = variants.iter().map(|v| v.name.clone()).collect();
315
+ println!(
316
+ "Plan: variants={:?} mode={}",
317
+ variant_names,
318
+ if copy { "remux" } else { "encode" }
 
 
 
 
 
319
  );
 
 
 
 
 
 
 
 
320
 
321
+ // 3. Start uploading segments as they appear — no post-encode tail.
322
+ let s3_prefix = format!("videos/{}", task_id);
323
+ let uploader = DirUploader::start(storage.clone(), output_dir.clone(), s3_prefix.clone());
324
 
325
+ status(
326
+ scheduler.as_ref(),
327
+ &task_id,
328
+ ENCODE_BASE_PCT,
329
+ if copy {
330
+ "Packaging video into adaptive streams..."
331
+ } else {
332
+ "Compressing and optimizing video..."
333
+ },
334
+ )
335
+ .await;
336
+
337
+ let args = build_args(video_path, &output_dir, &probe, &variants, copy, &config);
338
+ let encode_res = run_ffmpeg_with_progress(
339
+ &args,
340
+ probe.duration,
341
+ scheduler.as_ref(),
342
+ &task_id,
343
+ ENCODE_BASE_PCT,
344
+ ENCODE_SPAN_PCT,
345
+ )
346
+ .await;
347
+
348
+ // Drain whatever ffmpeg just wrote (playlists land at the end).
349
+ let upload_res = uploader.finish().await;
350
+
351
+ if let Err(e) = encode_res {
352
+ if let Some(ref sched) = scheduler {
353
+ clear_job_progress(sched, &task_id).await;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  }
355
+ return Err(e);
356
  }
357
+ upload_res?;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
 
359
+ // 4. Thumbnail next to the source (legacy path; auto-cover is handled by the worker)
360
+ if !skip_thumbnail {
361
+ status(scheduler.as_ref(), &task_id, 92, "Generating thumbnail...").await;
362
+ if let Err(e) = generate_thumbnail(video_path).await {
363
+ eprintln!("Legacy thumbnail generation failed: {}", e);
 
 
364
  }
365
  }
366
 
367
+ Ok((output_dir, variant_names))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  }
369
 
370
+ async fn status(
371
+ scheduler: Option<&WeightedScheduler>,
372
+ task_id: &str,
373
+ progress: u32,
374
+ message: &str,
375
+ ) {
376
+ if let Some(sched) = scheduler {
377
+ let status = TaskStatus {
378
+ progress,
379
+ status: "processing".to_string(),
380
+ message: message.to_string(),
381
+ cover_url: None,
382
+ cover_source: None,
383
+ variants: None,
384
+ };
385
+ let status_json = serde_json::to_string(&status).unwrap_or_default();
386
+ let _: () = sched
387
+ .client()
388
+ .set(
389
+ format!("task:status:{}", task_id),
390
+ status_json,
391
+ Some(fred::types::Expiration::EX(86400)),
392
+ None,
393
+ false,
394
+ )
395
+ .await
396
+ .unwrap_or_default();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
397
  }
 
398
  }
399
 
400
+ /// Build the ffmpeg invocation for either a remux (`copy = true`) or a real encode.
401
+ fn build_args(
402
  input: &str,
403
  output_dir: &str,
404
+ probe: &Probe,
405
+ variants: &[Variant],
406
+ copy: bool,
407
  config: &TranscodingConfig,
408
+ ) -> Vec<String> {
409
+ let n = variants.len();
410
+ let mut args: Vec<String> = vec!["-i".into(), input.into()];
411
+
412
+ if !copy {
413
+ args.extend([
414
+ "-preset".to_string(),
415
+ config.preset.clone(),
416
+ "-crf".to_string(),
417
+ config.crf.clone(),
418
+ ]);
419
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
 
421
+ args.extend([
 
 
 
 
 
 
 
 
422
  "-f".into(),
423
  "hls".into(),
424
  "-hls_time".into(),
425
+ HLS_SEGMENT_SECS.to_string(),
426
  "-hls_playlist_type".into(),
427
  "vod".into(),
428
  "-master_pl_name".into(),
429
  "master.m3u8".into(),
430
+ ]);
 
 
431
 
432
+ // Threads per encoder: with several renditions in one process, letting each
433
+ // x264 instance spawn for every core oversubscribes a 2-vCPU Space.
434
+ let cores = std::thread::available_parallelism()
435
+ .map(|c| c.get())
436
+ .unwrap_or(2);
437
+ let threads_per_variant = (cores / n.max(1)).max(1);
438
+
439
+ if copy {
440
+ args.extend(["-map".into(), "0:v:0".into()]);
441
+ args.extend(["-c".into(), "copy".into()]);
442
+ } else if n == 1 {
443
+ let filter = format!("[0:v]scale=w=-2:h={}[v0out]", variants[0].height);
444
+ args.extend(["-filter_complex".into(), filter]);
445
+ args.extend([
446
+ "-map".into(),
447
+ "[v0out]".into(),
448
+ "-c:v:0".into(),
449
+ "libx264".into(),
450
+ "-b:v:0".into(),
451
+ variants[0].bitrate.to_string(),
452
+ "-threads:v:0".to_string(),
453
+ threads_per_variant.to_string(),
454
+ ]);
455
  } else {
456
+ let mut filter = format!("[0:v]split={}", n);
457
+ for i in 0..n {
458
+ filter.push_str(&format!("[v{}]", i));
459
+ }
460
+ filter.push(';');
461
+ for i in 0..n {
462
+ filter.push_str(&format!(
463
+ " [v{}]scale=w=-2:h={}[v{}out];",
464
+ i, variants[i].height, i
465
+ ));
466
+ }
467
+ args.extend(["-filter_complex".into(), filter]);
468
+
469
+ for (i, variant) in variants.iter().enumerate() {
470
+ args.extend([
471
+ "-map".to_string(),
472
+ format!("[v{}out]", i),
473
+ format!("-c:v:{}", i),
474
+ "libx264".to_string(),
475
+ format!("-b:v:{}", i),
476
+ variant.bitrate.to_string(),
477
+ format!("-threads:v:{}", i),
478
+ threads_per_variant.to_string(),
479
+ ]);
480
+ }
481
  }
482
 
483
+ // ── Audio ────────────────────────────────────────────────────────────────
484
+ // Each HLS variant needs its OWN audio output stream. Map the source audio
485
+ // once per variant with unique a:N so the muxer writes independent AAC
486
+ // streams into each segment set. Copy mode keeps the source audio codec.
487
+ if probe.has_audio {
488
+ for _ in 0..n {
489
  args.push("-map".into());
490
+ args.push("0:a:0".into());
491
  }
492
+ if !copy {
493
+ for i in 0..n {
494
+ args.push(format!("-c:a:{}", i));
495
+ args.push("aac".into());
496
+ args.push(format!("-b:a:{}", i));
497
+ args.push("128k".into());
498
+ }
499
  }
500
  }
501
 
502
+ // ── HLS naming ───────────────────────────────────────────────────────────
503
+ let stream_map = if probe.has_audio {
504
+ variants
505
+ .iter()
506
+ .enumerate()
507
+ .map(|(i, v)| format!("v:{},a:{},name:{}", i, i, v.name))
508
+ .collect::<Vec<_>>()
509
+ .join(" ")
510
+ } else {
511
+ variants
512
+ .iter()
513
+ .enumerate()
514
+ .map(|(i, v)| format!("v:{},name:{}", i, v.name))
515
+ .collect::<Vec<_>>()
516
+ .join(" ")
517
+ };
518
 
519
  args.extend([
520
  "-hls_segment_filename".to_string(),
521
+ format!("{}/%v_%03d.ts", output_dir),
522
  "-var_stream_map".to_string(),
523
  stream_map,
524
+ format!("{}/%v.m3u8", output_dir),
525
  ]);
526
 
527
+ args
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
528
  }
529
 
530
+ /// Spawn ffmpeg with `-progress pipe:1`, map `out_time` onto the `base..base+span`
531
+ /// progress band, and throttle Redis writes to ~1/sec.
 
 
 
532
  async fn run_ffmpeg_with_progress(
533
  args: &[String],
534
  duration_secs: f64,
535
  scheduler: Option<&WeightedScheduler>,
536
  task_id: &str,
537
+ base: u32,
538
+ span: u32,
539
  ) -> Result<()> {
540
  // Machine-readable progress on stdout; keep stderr for errors (drained so the pipe never blocks).
541
  let mut full_args: Vec<String> = vec![
 
589
  if force || last_report.elapsed() >= PROGRESS_REPORT_INTERVAL {
590
  if duration_secs > 0.0 {
591
  let current_time_seconds = current_out_us as f64 / 1_000_000.0;
592
+ let ratio = (current_time_seconds / duration_secs).clamp(0.0, 1.0);
593
+ // Stay below base+span until process exit confirms success.
594
+ let progress_percent = base + (ratio * span as f64) as u32;
595
  if let Some(sched) = scheduler {
596
  set_job_progress(sched, task_id, progress_percent).await;
597
  }
 
612
  return Err(anyhow!("FFmpeg failed: {}", err_text));
613
  }
614
 
 
 
 
615
  Ok(())
616
  }
617
 
618
+ /// Background directory watcher: uploads each HLS artifact as soon as its size
619
+ /// stops changing, so S3 transfer overlaps the encode instead of following it.
620
+ struct DirUploader {
621
+ stop: Arc<AtomicBool>,
622
+ handle: tokio::task::JoinHandle<Result<()>>,
623
+ }
624
+
625
+ impl DirUploader {
626
+ fn start(storage: Arc<StorageManager>, dir: String, prefix: String) -> Self {
627
+ let stop = Arc::new(AtomicBool::new(false));
628
+ let handle = tokio::spawn({
629
+ let stop = stop.clone();
630
+ async move { run_dir_uploader(storage, dir, prefix, stop).await }
631
+ });
632
+ Self { stop, handle }
633
+ }
634
+
635
+ async fn finish(self) -> Result<()> {
636
+ self.stop.store(true, Ordering::Relaxed);
637
+ match self.handle.await {
638
+ Ok(res) => res,
639
+ Err(e) => Err(anyhow!("segment uploader panicked: {}", e)),
640
+ }
641
+ }
642
+ }
643
+
644
+ async fn run_dir_uploader(
645
+ storage: Arc<StorageManager>,
646
+ dir: String,
647
+ prefix: String,
648
+ stop: Arc<AtomicBool>,
649
+ ) -> Result<()> {
650
+ let concurrency = std::env::var("UPLOAD_CONCURRENCY")
651
+ .ok()
652
+ .and_then(|v| v.parse::<usize>().ok())
653
+ .filter(|v| *v > 0)
654
+ .unwrap_or(12);
655
+
656
+ // name -> last observed size. A file is uploaded once its size is stable
657
+ // across two polls (i.e. ffmpeg has finished writing it).
658
+ let mut sizes: HashMap<String, u64> = HashMap::new();
659
+ let mut queued: HashSet<String> = HashSet::new();
660
+ let mut inflight: JoinSet<Result<()>> = JoinSet::new();
661
+ let mut first_err: Option<anyhow::Error> = None;
662
+
663
+ loop {
664
+ while let Some(res) = inflight.try_join_next() {
665
+ match res {
666
+ Ok(Ok(())) => {}
667
+ Ok(Err(e)) => {
668
+ if first_err.is_none() {
669
+ first_err = Some(e);
670
+ }
671
+ }
672
+ Err(e) => {
673
+ if first_err.is_none() {
674
+ first_err = Some(anyhow!("upload task failed: {}", e));
675
+ }
676
+ }
677
+ }
678
+ }
679
+
680
+ let stopping = stop.load(Ordering::Relaxed);
681
+
682
+ if inflight.len() < concurrency {
683
+ if let Ok(mut entries) = fs::read_dir(&dir).await {
684
+ loop {
685
+ let entry = match entries.next_entry().await {
686
+ Ok(Some(e)) => e,
687
+ Ok(None) => break,
688
+ Err(_) => break,
689
+ };
690
+ let path = entry.path();
691
+ if !path.is_file() {
692
+ continue;
693
+ }
694
+ let name = match path.file_name().and_then(|n| n.to_str()) {
695
+ Some(n) => n.to_string(),
696
+ None => continue,
697
+ };
698
+ if queued.contains(&name) {
699
+ continue;
700
+ }
701
+
702
+ let size = entry.metadata().await.map(|m| m.len()).unwrap_or(0);
703
+ let stable = sizes.get(&name) == Some(&size);
704
+ sizes.insert(name.clone(), size);
705
+
706
+ // Skip files ffmpeg is still growing (and empty placeholders).
707
+ if (!stable && !stopping) || size == 0 {
708
+ continue;
709
+ }
710
+
711
+ queued.insert(name.clone());
712
+ let storage = storage.clone();
713
+ let key = format!("{}/{}", prefix, name);
714
+ inflight.spawn(async move { storage.upload_file(&path, &key).await });
715
+ }
716
+ }
717
+ }
718
+
719
+ if stopping && inflight.is_empty() {
720
+ break;
721
+ }
722
+
723
+ tokio::time::sleep(Duration::from_millis(250)).await;
724
+ }
725
+
726
+ match first_err {
727
+ Some(e) => Err(e),
728
+ None => Ok(()),
729
+ }
730
+ }
731
+
732
+ /// Probe width/height/audio/duration/codecs in a single ffprobe invocation.
733
+ async fn probe_video(video_path: &str) -> Result<Probe> {
734
  let output = Command::new("ffprobe")
735
  .args([
736
  "-v",
737
  "error",
 
 
738
  "-show_entries",
739
+ "stream=codec_type,codec_name,width,height:format=duration",
740
  "-of",
741
  "json",
742
+ video_path,
743
  ])
744
  .output()
745
  .await?;
 
747
  if !output.status.success() {
748
  return Err(anyhow!(
749
  "ffprobe failed for {}: {}",
750
+ video_path,
751
  String::from_utf8_lossy(&output.stderr).trim()
752
  ));
753
  }
754
 
755
+ let raw = String::from_utf8_lossy(&output.stdout);
756
+ let json: serde_json::Value = serde_json::from_str(&raw)
757
+ .map_err(|e| anyhow!("Invalid ffprobe JSON ({}): {}", e, raw.trim()))?;
758
+
759
+ let duration = json
760
+ .get("format")
761
+ .and_then(|f| f.get("duration"))
762
+ .and_then(|d| d.as_str())
763
+ .and_then(|d| d.parse::<f64>().ok())
764
+ .filter(|d| d.is_finite() && *d > 0.0)
765
+ .unwrap_or(0.0);
766
+
767
+ let streams = json
768
+ .get("streams")
769
+ .and_then(|v| v.as_array())
770
+ .ok_or_else(|| anyhow!("ffprobe returned no streams: {}", raw.trim()))?;
771
+
772
+ let mut width = 0i32;
773
+ let mut height = 0i32;
774
+ let mut video_codec = String::new();
775
+ let mut audio_codec: Option<String> = None;
776
+ let mut has_audio = false;
777
+
778
+ for stream in streams {
779
+ let kind = stream.get("codec_type").and_then(|v| v.as_str()).unwrap_or("");
780
+ match kind {
781
+ "video" if width == 0 => {
782
+ let w = stream.get("width").and_then(|v| v.as_i64()).unwrap_or(0);
783
+ let h = stream.get("height").and_then(|v| v.as_i64()).unwrap_or(0);
784
+ if w > 0 && h > 0 {
785
+ width = w as i32;
786
+ height = h as i32;
787
+ video_codec = stream
788
+ .get("codec_name")
789
+ .and_then(|v| v.as_str())
790
+ .unwrap_or("")
791
+ .to_string();
792
+ }
793
+ }
794
+ "audio" if !has_audio => {
795
+ has_audio = true;
796
+ audio_codec = stream
797
+ .get("codec_name")
798
+ .and_then(|v| v.as_str())
799
+ .map(|s| s.to_string());
800
+ }
801
+ _ => {}
802
+ }
803
+ }
804
+
805
+ if width == 0 || height == 0 {
806
+ return Err(anyhow!(
807
+ "ffprobe returned no usable width/height: {}",
808
+ raw.trim()
809
+ ));
810
+ }
811
+
812
+ Ok(Probe {
813
+ width,
814
+ height,
815
+ has_audio,
816
+ duration,
817
+ video_codec,
818
+ audio_codec,
819
+ })
820
+ }
821
+
822
+ /// Pick the first width/height pair from `ffprobe -of json -show_entries stream=width,height`.
823
+ ///
824
+ /// JSON is used instead of `-of csv=s=x:p=0` because the CSV writer can emit
825
+ /// extra sections/fields depending on the container (e.g. QuickTime timecode
826
+ /// tracks and MPEG-TS programs produce multiple lines, and some files end with
827
+ /// a bare separator like `1080x1080x`). Splitting the whole stdout on 'x' then
828
+ /// rejects perfectly valid values.
829
+ #[cfg(test)]
830
+ fn parse_dimensions(stdout: &[u8]) -> Result<(i32, i32)> {
831
+ let raw = String::from_utf8_lossy(stdout);
832
+ let json: serde_json::Value = serde_json::from_str(&raw)
833
+ .map_err(|e| anyhow!("Invalid ffprobe JSON ({}): {}", e, raw.trim()))?;
834
+
835
+ let streams = json
836
+ .get("streams")
837
+ .and_then(|v| v.as_array())
838
+ .ok_or_else(|| anyhow!("ffprobe returned no streams: {}", raw.trim()))?;
839
+
840
+ for stream in streams {
841
+ let width = stream.get("width").and_then(|v| v.as_i64());
842
+ let height = stream.get("height").and_then(|v| v.as_i64());
843
+ if let (Some(w), Some(h)) = (width, height) {
844
+ if w > 0 && h > 0 {
845
+ return Ok((w as i32, h as i32));
846
+ }
847
+ }
848
+ }
849
+
850
+ Err(anyhow!(
851
+ "ffprobe returned no usable width/height: {}",
852
+ raw.trim()
853
+ ))
854
  }
855
 
856
  async fn generate_thumbnail(video_path: &str) -> Result<()> {
 
860
  }
861
 
862
  /// Seek ~`pct` into the video (default 10%) and write a single JPEG frame.
 
 
863
  pub async fn extract_cover_frame(video_path: &str, out_jpg: &str, pct: f64) -> Result<()> {
864
+ let duration = probe_video(video_path)
865
+ .await
866
+ .map(|p| p.duration)
867
+ .unwrap_or(0.0);
868
+
869
  let seek_secs = if duration > 0.5 {
870
  (duration * pct).clamp(0.0, (duration - 0.05).max(0.0))
871
  } else {
 
909
  }
910
 
911
  /// Auto cover: frame at ~10% duration → JPEG → S3 `thumbnails/{task_id}.jpg`.
912
+ ///
913
+ /// Prefers pulling the frame out of an already-encoded HLS segment (cheap, and
914
+ /// the bytes are already local) and only falls back to re-reading the source.
915
  /// Returns the S3 key for inclusion in the Redis completion payload.
916
  pub async fn generate_and_upload_auto_cover(
917
  video_path: &str,
918
+ output_dir: &str,
919
  task_id: &str,
920
  storage: &StorageManager,
921
  ) -> Result<String> {
922
  let cover_local = format!("{}_cover.jpg", video_path);
923
+
924
+ let source = pick_cover_source(video_path, output_dir).await;
925
+ extract_cover_frame(&source, &cover_local, 0.1).await?;
926
 
927
  let cover_key = format!("thumbnails/{}.jpg", task_id);
928
  storage
 
936
  Ok(cover_key)
937
  }
938
 
939
+ /// Choose the cheapest file that contains a representative frame.
940
+ async fn pick_cover_source(video_path: &str, output_dir: &str) -> String {
941
+ let entries = match fs::read_dir(output_dir).await {
942
+ Ok(e) => e,
943
+ Err(_) => return video_path.to_string(),
944
+ };
945
+
946
+ let mut segments: Vec<(u32, std::path::PathBuf)> = Vec::new();
947
+ let mut entries = entries;
948
+ while let Ok(Some(entry)) = entries.next_entry().await {
949
+ let path = entry.path();
950
+ if path.extension().and_then(|e| e.to_str()) != Some("ts") {
951
+ continue;
952
+ }
953
+ let name = match path.file_name().and_then(|n| n.to_str()) {
954
+ Some(n) => n,
955
+ None => continue,
956
+ };
957
+ // "<variant>_<index>.ts"
958
+ if let Some(idx) = name
959
+ .rsplit_once('_')
960
+ .and_then(|(_, tail)| tail.trim_end_matches(".ts").parse::<u32>().ok())
961
+ {
962
+ segments.push((idx, path));
963
+ }
964
+ }
965
+
966
+ if segments.is_empty() {
967
+ return video_path.to_string();
968
+ }
969
+
970
+ // Roughly 10% into the video, expressed in segments.
971
+ let total = segments.iter().map(|(i, _)| *i).max().unwrap_or(0) + 1;
972
+ let target = (total / 10).min(total.saturating_sub(1));
973
+ segments.sort_by_key(|(idx, _)| idx.abs_diff(target));
974
+
975
+ segments
976
+ .into_iter()
977
+ .next()
978
+ .map(|(_, p)| p.to_string_lossy().to_string())
979
+ .unwrap_or_else(|| video_path.to_string())
980
+ }
981
+
982
  #[cfg(test)]
983
  mod tests {
984
+ use super::{label_for, parse_dimensions, plan_variants, Probe, UserTier};
985
+
986
+ fn probe(height: i32, codec: &str) -> Probe {
987
+ Probe {
988
+ width: (height as f64 * 16.0 / 9.0) as i32,
989
+ height,
990
+ has_audio: true,
991
+ duration: 60.0,
992
+ video_codec: codec.to_string(),
993
+ audio_codec: Some("aac".to_string()),
994
+ }
995
+ }
996
 
997
  #[test]
998
  fn picks_first_stream_with_dimensions() {
 
1020
  fn rejects_non_json_output() {
1021
  assert!(parse_dimensions(b"1080x1080x").is_err());
1022
  }
1023
+
1024
+ #[test]
1025
+ fn h264_within_cap_is_passthrough() {
1026
+ let (variants, copy) = plan_variants("home", &UserTier::Free, &probe(720, "h264"));
1027
+ assert!(copy);
1028
+ assert_eq!(variants.len(), 1);
1029
+ assert_eq!(variants[0].name, "720p");
1030
+ }
1031
+
1032
+ #[test]
1033
+ fn h264_above_cap_must_encode() {
1034
+ let (variants, copy) = plan_variants("home", &UserTier::Free, &probe(1080, "h264"));
1035
+ assert!(!copy);
1036
+ assert_eq!(variants.len(), 1);
1037
+ assert_eq!(variants[0].height, 720);
1038
+ }
1039
+
1040
+ #[test]
1041
+ fn low_resolution_source_is_never_upscaled() {
1042
+ let (variants, _) = plan_variants("home", &UserTier::Free, &probe(360, "hevc"));
1043
+ assert_eq!(variants.len(), 1);
1044
+ assert_eq!(variants[0].height, 360);
1045
+ }
1046
+
1047
+ #[test]
1048
+ fn pro_keeps_the_ladder() {
1049
+ let (variants, _) = plan_variants("home", &UserTier::Pro, &probe(1080, "hevc"));
1050
+ let names: Vec<_> = variants.iter().map(|v| v.name.as_str()).collect();
1051
+ assert_eq!(names, vec!["1080p", "720p", "480p"]);
1052
+ }
1053
+
1054
+ #[test]
1055
+ fn labels_bucket_by_height() {
1056
+ assert_eq!(label_for(1080), "1080p");
1057
+ assert_eq!(label_for(720), "720p");
1058
+ assert_eq!(label_for(360), "480p");
1059
+ }
1060
  }
src/worker.rs CHANGED
@@ -1,5 +1,5 @@
1
  use std::sync::Arc;
2
- use tokio::sync::Semaphore;
3
  use sysinfo::{System, SystemExt};
4
  use crate::queue::WeightedScheduler;
5
  use fred::interfaces::KeysInterface;
@@ -27,8 +27,8 @@ impl WorkerPool {
27
  println!("Worker Pool started. Polling for tasks...");
28
 
29
  loop {
30
- // Wait for a slot to be available before even pulling a task
31
- // This prevents filling RAM with tasks that are just waiting
32
  let permit = self.semaphore.clone().acquire_owned().await.unwrap();
33
 
34
  match self.scheduler.next_task().await {
@@ -50,7 +50,7 @@ impl WorkerPool {
50
  }
51
 
52
  /// Process one queued video job end-to-end:
53
- /// download → transcode → resolve cover (custom pass-through or auto-generate) → Redis status.
54
  async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
55
  let task_id = task.task_id.clone();
56
  let s3_key = task.video_id.clone();
@@ -70,9 +70,10 @@ async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
70
  let is_custom = cover_source == "custom";
71
 
72
  let storage = match StorageManager::new().await {
73
- Ok(s) => s,
74
  Err(e) => {
75
  eprintln!("Failed to initialize StorageManager for task {}: {}", task_id, e);
 
76
  return;
77
  }
78
  };
@@ -81,28 +82,60 @@ async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
81
  Ok(f) => f,
82
  Err(e) => {
83
  eprintln!("Failed to create temp file for task {}: {}", task_id, e);
 
84
  return;
85
  }
86
  };
87
  let temp_path = temp_file.path().to_str().unwrap().to_string();
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  println!("Downloading {} from S3 to {}", s3_key, temp_path);
90
- if let Err(e) = storage.download_file(&s3_key, temp_file.path()).await {
 
 
 
 
91
  eprintln!("Download failed for task {}: {}", task_id, e);
92
- write_task_status(
93
- &scheduler,
94
- &task_id,
95
- TaskStatus {
96
- progress: 0,
97
- status: "error".to_string(),
98
- message: format!("Download failed: {}", e),
99
- cover_url: None,
100
- cover_source: Some(cover_source.clone()),
101
- },
102
- )
103
- .await;
104
  return;
105
  }
 
 
106
 
107
  // Transcode only — cover handling is separate (skip legacy thumbnail/{task_id}.jpg path)
108
  for attempt in 1..=3 {
@@ -118,18 +151,19 @@ async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
118
  true, // always skip legacy concurrent thumb; we resolve cover below
119
  Some(scheduler.clone()),
120
  task_id.clone(),
 
121
  )
122
  .await;
123
 
124
  match res {
125
- Ok(()) => {
126
  println!(
127
- "Completed transcode for task {} (cover_source={})",
128
- task_id, cover_source
129
  );
130
  transcoder::set_job_progress(&scheduler, &task_id, 100).await;
131
 
132
- // 2–3) Resolve cover_url
133
  let cover_url = if is_custom {
134
  // Custom: no generation — pass through already-uploaded S3 key
135
  let key = cover_s3_key.clone().unwrap_or_else(|| {
@@ -138,11 +172,12 @@ async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
138
  println!("Using custom cover (skip generation): {}", key);
139
  key
140
  } else {
141
- // Auto (or missing): extract ~10% frame, JPEG, upload thumbnails/{task_id}.jpg
142
  match transcoder::generate_and_upload_auto_cover(
143
  &temp_path,
 
144
  &task_id,
145
- &storage,
146
  )
147
  .await
148
  {
@@ -153,16 +188,11 @@ async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
153
  task_id, e
154
  );
155
  transcoder::clear_job_progress(&scheduler, &task_id).await;
156
- write_task_status(
157
  &scheduler,
158
  &task_id,
159
- TaskStatus {
160
- progress: 0,
161
- status: "error".to_string(),
162
- message: format!("Cover generation failed: {}", e),
163
- cover_url: None,
164
- cover_source: Some(cover_source.clone()),
165
- },
166
  )
167
  .await;
168
  return;
@@ -171,7 +201,7 @@ async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
171
  };
172
 
173
  // 4) Completion payload for Celery /status consumers
174
- write_task_status(
175
  &scheduler,
176
  &task_id,
177
  TaskStatus {
@@ -180,6 +210,7 @@ async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
180
  message: "Video live and distributed globally!".to_string(),
181
  cover_url: Some(cover_url),
182
  cover_source: Some(cover_source.clone()),
 
183
  },
184
  )
185
  .await;
@@ -188,16 +219,11 @@ async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
188
  Err(e) if attempt == 3 => {
189
  eprintln!("Failed Task {} after 3 attempts: {}", task_id, e);
190
  transcoder::clear_job_progress(&scheduler, &task_id).await;
191
- write_task_status(
192
  &scheduler,
193
  &task_id,
194
- TaskStatus {
195
- progress: 0,
196
- status: "error".to_string(),
197
- message: format!("Final error: {}", e),
198
- cover_url: None,
199
- cover_source: Some(cover_source.clone()),
200
- },
201
  )
202
  .await;
203
  }
@@ -207,9 +233,33 @@ async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
207
  }
208
  }
209
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  }
211
 
212
- async fn write_task_status(scheduler: &WeightedScheduler, task_id: &str, status: TaskStatus) {
213
  let status_json = serde_json::to_string(&status).unwrap_or_else(|_| {
214
  r#"{"progress":0,"status":"error","message":"serialize failed"}"#.to_string()
215
  });
@@ -227,6 +277,15 @@ async fn write_task_status(scheduler: &WeightedScheduler, task_id: &str, status:
227
  }
228
 
229
  fn calculate_max_processes() -> usize {
 
 
 
 
 
 
 
 
 
230
  let mut sys = System::new_all();
231
  sys.refresh_all();
232
 
 
1
  use std::sync::Arc;
2
+ use tokio::sync::{mpsc, Semaphore};
3
  use sysinfo::{System, SystemExt};
4
  use crate::queue::WeightedScheduler;
5
  use fred::interfaces::KeysInterface;
 
27
  println!("Worker Pool started. Polling for tasks...");
28
 
29
  loop {
30
+ // Wait for a slot to be available before even pulling a task.
31
+ // This prevents filling RAM with tasks that are just waiting.
32
  let permit = self.semaphore.clone().acquire_owned().await.unwrap();
33
 
34
  match self.scheduler.next_task().await {
 
50
  }
51
 
52
  /// Process one queued video job end-to-end:
53
+ /// download → package/transcode → cover → Redis status.
54
  async fn process_video_job(scheduler: WeightedScheduler, task: VideoTask) {
55
  let task_id = task.task_id.clone();
56
  let s3_key = task.video_id.clone();
 
70
  let is_custom = cover_source == "custom";
71
 
72
  let storage = match StorageManager::new().await {
73
+ Ok(s) => Arc::new(s),
74
  Err(e) => {
75
  eprintln!("Failed to initialize StorageManager for task {}: {}", task_id, e);
76
+ fail_task(&scheduler, &task_id, &cover_source, format!("Storage initialization failed: {}", e)).await;
77
  return;
78
  }
79
  };
 
82
  Ok(f) => f,
83
  Err(e) => {
84
  eprintln!("Failed to create temp file for task {}: {}", task_id, e);
85
+ fail_task(&scheduler, &task_id, &cover_source, format!("Temp file failed: {}", e)).await;
86
  return;
87
  }
88
  };
89
  let temp_path = temp_file.path().to_str().unwrap().to_string();
90
 
91
+ // 2) Stream the source to disk, reporting progress so the UI starts moving
92
+ // immediately instead of sitting at 0% until the encode begins.
93
+ transcoder::set_job_progress(&scheduler, &task_id, 2).await;
94
+ write_status(
95
+ &scheduler,
96
+ &task_id,
97
+ TaskStatus {
98
+ progress: 2,
99
+ status: "processing".to_string(),
100
+ message: "Downloading source video...".to_string(),
101
+ cover_url: None,
102
+ cover_source: Some(cover_source.clone()),
103
+ variants: None,
104
+ },
105
+ )
106
+ .await;
107
+
108
+ let (tx, mut rx) = mpsc::unbounded_channel::<(u64, u64)>();
109
+ let progress_sched = scheduler.clone();
110
+ let progress_task = task_id.clone();
111
+ let progress_pump = tokio::spawn(async move {
112
+ let mut last_pct = 0u32;
113
+ while let Some((done, total)) = rx.recv().await {
114
+ let pct = if total > 0 {
115
+ (2.0 + (done as f64 / total as f64) * 12.0) as u32
116
+ } else {
117
+ 8
118
+ };
119
+ let pct = pct.min(14);
120
+ if pct != last_pct {
121
+ last_pct = pct;
122
+ transcoder::set_job_progress(&progress_sched, &progress_task, pct).await;
123
+ }
124
+ }
125
+ });
126
+
127
  println!("Downloading {} from S3 to {}", s3_key, temp_path);
128
+ if let Err(e) = storage
129
+ .download_file(&s3_key, temp_file.path(), Some(tx))
130
+ .await
131
+ {
132
+ progress_pump.await.ok();
133
  eprintln!("Download failed for task {}: {}", task_id, e);
134
+ fail_task(&scheduler, &task_id, &cover_source, format!("Download failed: {}", e)).await;
 
 
 
 
 
 
 
 
 
 
 
135
  return;
136
  }
137
+ progress_pump.await.ok();
138
+ transcoder::set_job_progress(&scheduler, &task_id, 15).await;
139
 
140
  // Transcode only — cover handling is separate (skip legacy thumbnail/{task_id}.jpg path)
141
  for attempt in 1..=3 {
 
151
  true, // always skip legacy concurrent thumb; we resolve cover below
152
  Some(scheduler.clone()),
153
  task_id.clone(),
154
+ storage.clone(),
155
  )
156
  .await;
157
 
158
  match res {
159
+ Ok((output_dir, variants)) => {
160
  println!(
161
+ "Completed transcode for task {} (variants={:?}, cover_source={})",
162
+ task_id, variants, cover_source
163
  );
164
  transcoder::set_job_progress(&scheduler, &task_id, 100).await;
165
 
166
+ // 3) Resolve cover_url
167
  let cover_url = if is_custom {
168
  // Custom: no generation — pass through already-uploaded S3 key
169
  let key = cover_s3_key.clone().unwrap_or_else(|| {
 
172
  println!("Using custom cover (skip generation): {}", key);
173
  key
174
  } else {
175
+ // Auto: grab a frame from an encoded segment, fall back to the source
176
  match transcoder::generate_and_upload_auto_cover(
177
  &temp_path,
178
+ &output_dir,
179
  &task_id,
180
+ storage.as_ref(),
181
  )
182
  .await
183
  {
 
188
  task_id, e
189
  );
190
  transcoder::clear_job_progress(&scheduler, &task_id).await;
191
+ fail_task(
192
  &scheduler,
193
  &task_id,
194
+ &cover_source,
195
+ format!("Cover generation failed: {}", e),
 
 
 
 
 
196
  )
197
  .await;
198
  return;
 
201
  };
202
 
203
  // 4) Completion payload for Celery /status consumers
204
+ write_status(
205
  &scheduler,
206
  &task_id,
207
  TaskStatus {
 
210
  message: "Video live and distributed globally!".to_string(),
211
  cover_url: Some(cover_url),
212
  cover_source: Some(cover_source.clone()),
213
+ variants: Some(variants),
214
  },
215
  )
216
  .await;
 
219
  Err(e) if attempt == 3 => {
220
  eprintln!("Failed Task {} after 3 attempts: {}", task_id, e);
221
  transcoder::clear_job_progress(&scheduler, &task_id).await;
222
+ fail_task(
223
  &scheduler,
224
  &task_id,
225
+ &cover_source,
226
+ format!("Final error: {}", e),
 
 
 
 
 
227
  )
228
  .await;
229
  }
 
233
  }
234
  }
235
  }
236
+
237
+ // Explicitly drop the temp file so disk space is returned before the slot frees.
238
+ drop(temp_file);
239
+ }
240
+
241
+ async fn fail_task(
242
+ scheduler: &WeightedScheduler,
243
+ task_id: &str,
244
+ cover_source: &str,
245
+ message: String,
246
+ ) {
247
+ write_status(
248
+ scheduler,
249
+ task_id,
250
+ TaskStatus {
251
+ progress: 0,
252
+ status: "error".to_string(),
253
+ message,
254
+ cover_url: None,
255
+ cover_source: Some(cover_source.to_string()),
256
+ variants: None,
257
+ },
258
+ )
259
+ .await;
260
  }
261
 
262
+ async fn write_status(scheduler: &WeightedScheduler, task_id: &str, status: TaskStatus) {
263
  let status_json = serde_json::to_string(&status).unwrap_or_else(|_| {
264
  r#"{"progress":0,"status":"error","message":"serialize failed"}"#.to_string()
265
  });
 
277
  }
278
 
279
  fn calculate_max_processes() -> usize {
280
+ // Explicit override wins (useful when the host reports shared/throttled CPUs).
281
+ if let Ok(raw) = std::env::var("MAX_CONCURRENT_JOBS") {
282
+ if let Ok(v) = raw.parse::<usize>() {
283
+ if v > 0 {
284
+ return v;
285
+ }
286
+ }
287
+ }
288
+
289
  let mut sys = System::new_all();
290
  sys.refresh_all();
291