Monteeq CI commited on
Commit
5beeefc
Β·
1 Parent(s): 48c9034

πŸš€ Deploy from GitHub @ c7c11eb07b319cec1e9d85c4c05969ab77322faf

Browse files

Triggered by: Smasduq
Message: Merge pull request #17 from Monteeq/feat/async-upload-jobs-gunicorn

Feat/async upload jobs gunicorn

Files changed (4) hide show
  1. src/main.rs +21 -1
  2. src/models.rs +15 -0
  3. src/transcoder.rs +459 -75
  4. src/worker.rs +187 -86
src/main.rs CHANGED
@@ -29,6 +29,14 @@ struct ProcessRequest {
29
  tier: UserTier,
30
  #[serde(default)]
31
  skip_thumbnail: bool,
 
 
 
 
 
 
 
 
32
  }
33
 
34
  struct AppState {
@@ -94,18 +102,28 @@ async fn process_video(
94
  State(state): State<Arc<AppState>>,
95
  Json(payload): Json<ProcessRequest>
96
  ) -> Json<serde_json::Value> {
 
 
 
 
 
 
97
  let task = VideoTask {
98
  video_id: payload.video_id,
99
  task_id: payload.task_id.clone(),
100
  target_format: payload.target_format,
101
  tier: payload.tier,
102
- skip_thumbnail: payload.skip_thumbnail,
 
 
103
  };
104
 
105
  let status = TaskStatus {
106
  progress: 0,
107
  status: "queued".to_string(),
108
  message: "Task added to priority queue".to_string(),
 
 
109
  };
110
 
111
  // Save status to Redis with 24h TTL
@@ -145,6 +163,8 @@ async fn get_status(
145
  progress: 0,
146
  status: "error".to_string(),
147
  message: "Failed to parse status".to_string(),
 
 
148
  });
149
  Json(Some(status))
150
  },
 
29
  tier: UserTier,
30
  #[serde(default)]
31
  skip_thumbnail: bool,
32
+ #[serde(default = "default_cover_source", alias = "coverSource")]
33
+ cover_source: String,
34
+ #[serde(default, alias = "coverS3Key")]
35
+ cover_s3_key: Option<String>,
36
+ }
37
+
38
+ fn default_cover_source() -> String {
39
+ "auto".to_string()
40
  }
41
 
42
  struct AppState {
 
102
  State(state): State<Arc<AppState>>,
103
  Json(payload): Json<ProcessRequest>
104
  ) -> Json<serde_json::Value> {
105
+ let cover_source = if payload.cover_source.trim().is_empty() {
106
+ if payload.skip_thumbnail { "custom".to_string() } else { "auto".to_string() }
107
+ } else {
108
+ payload.cover_source.clone()
109
+ };
110
+
111
  let task = VideoTask {
112
  video_id: payload.video_id,
113
  task_id: payload.task_id.clone(),
114
  target_format: payload.target_format,
115
  tier: payload.tier,
116
+ skip_thumbnail: payload.skip_thumbnail || cover_source == "custom",
117
+ cover_source: cover_source.clone(),
118
+ cover_s3_key: payload.cover_s3_key.clone(),
119
  };
120
 
121
  let status = TaskStatus {
122
  progress: 0,
123
  status: "queued".to_string(),
124
  message: "Task added to priority queue".to_string(),
125
+ cover_url: None,
126
+ cover_source: Some(cover_source),
127
  };
128
 
129
  // Save status to Redis with 24h TTL
 
163
  progress: 0,
164
  status: "error".to_string(),
165
  message: "Failed to parse status".to_string(),
166
+ cover_url: None,
167
+ cover_source: None,
168
  });
169
  Json(Some(status))
170
  },
src/models.rs CHANGED
@@ -16,6 +16,16 @@ pub struct VideoTask {
16
  pub tier: UserTier,
17
  #[serde(default)]
18
  pub skip_thumbnail: bool,
 
 
 
 
 
 
 
 
 
 
19
  }
20
 
21
  #[derive(Serialize, Deserialize, Clone, Debug)]
@@ -23,4 +33,9 @@ pub struct TaskStatus {
23
  pub progress: u32,
24
  pub status: String,
25
  pub message: String,
 
 
 
 
 
26
  }
 
16
  pub tier: UserTier,
17
  #[serde(default)]
18
  pub skip_thumbnail: bool,
19
+ /// "auto" (Rust generates) or "custom" (client already uploaded cover)
20
+ #[serde(default = "default_cover_source", alias = "coverSource")]
21
+ pub cover_source: String,
22
+ /// S3 key for a custom cover, e.g. covers/{job_id}.jpg
23
+ #[serde(default, alias = "coverS3Key")]
24
+ pub cover_s3_key: Option<String>,
25
+ }
26
+
27
+ fn default_cover_source() -> String {
28
+ "auto".to_string()
29
  }
30
 
31
  #[derive(Serialize, Deserialize, Clone, Debug)]
 
33
  pub progress: u32,
34
  pub status: String,
35
  pub message: String,
36
+ /// Public or storage-relative cover URL/key after processing
37
+ #[serde(default, skip_serializing_if = "Option::is_none")]
38
+ pub cover_url: Option<String>,
39
+ #[serde(default, skip_serializing_if = "Option::is_none")]
40
+ pub cover_source: Option<String>,
41
  }
src/transcoder.rs CHANGED
@@ -1,12 +1,20 @@
1
  use tokio::process::Command;
 
2
  use fred::interfaces::KeysInterface;
3
  use anyhow::{Result, anyhow};
4
  use std::path::Path;
 
 
5
  use tokio::fs;
6
  use crate::storage::StorageManager;
7
  use crate::models::{UserTier, TaskStatus};
8
  use crate::queue::WeightedScheduler;
9
 
 
 
 
 
 
10
  pub struct TranscodingConfig {
11
  pub preset: String,
12
  pub max_height: i32,
@@ -30,45 +38,124 @@ impl TranscodingConfig {
30
  }
31
  }
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  pub async fn process(
34
  _video_id: String, // Platform ID
35
  video_path: &str, // Local filesystem path
36
- format: &str,
37
  tier: UserTier,
38
- skip_thumbnail: bool,
39
- scheduler: Option<WeightedScheduler>,
40
- task_id: String // Processing Key
41
  ) -> Result<()> {
42
  println!("Starting processing for task_id={} video_path={}", task_id, video_path);
43
-
44
  // Check if file exists
45
  if !Path::new(video_path).exists() {
46
  return Err(anyhow!("Video file not found at path: {}", video_path));
47
  }
48
 
49
  let config = TranscodingConfig::for_tier(&tier);
50
-
51
  // 1. Metadata extraction
52
  if let Some(ref sched) = scheduler {
53
  let status = TaskStatus {
54
  progress: 5,
55
  status: "processing".to_string(),
56
  message: "Analyzing video streams and metadata...".to_string(),
 
 
57
  };
58
  let status_json = serde_json::to_string(&status).unwrap();
59
- let _: () = sched.client().set(format!("task:status:{}", task_id), status_json, Some(fred::types::Expiration::EX(86400)), None, false).await.unwrap_or_default();
 
 
 
 
 
 
 
 
 
 
60
  }
61
  println!("Extracting metadata for {}", video_path);
62
- let (width, height, has_audio) = match get_video_metadata(video_path).await {
63
  Ok(m) => m,
64
  Err(e) => {
65
  eprintln!("Metadata extraction failed for {}: {}", video_path, e);
 
 
 
66
  return Err(e);
67
  }
68
  };
69
  let aspect_ratio = width / height;
70
- println!("Metadata: width={} height={} has_audio={} aspect_ratio={}", width, height, has_audio, aspect_ratio);
71
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  // 2. Prep Output
73
  let output_dir = format!("{}_hls", video_path);
74
  if !Path::new(&output_dir).exists() {
@@ -76,7 +163,17 @@ pub async fn process(
76
  }
77
 
78
  // 3. Transcode + Thumbnail Concurrently
79
- let transcoding_fut = transcode_tiered(video_path, &output_dir, format, &config, scheduler.clone(), task_id.clone(), has_audio, &tier);
 
 
 
 
 
 
 
 
 
 
80
  let v_path = video_path.to_string();
81
  let thumbnail_fut = async move {
82
  if !skip_thumbnail {
@@ -88,9 +185,17 @@ pub async fn process(
88
 
89
  // Run both. Pro users might benefit from faster total completion time
90
  let (trans_res, thumb_res) = tokio::join!(transcoding_fut, thumbnail_fut);
91
-
92
- trans_res?;
93
- thumb_res?;
 
 
 
 
 
 
 
 
94
 
95
  // 4. Upload to Storage
96
  match StorageManager::new().await {
@@ -101,37 +206,61 @@ pub async fn process(
101
  progress: 90,
102
  status: "processing".to_string(),
103
  message: "Syncing video segments to edge nodes...".to_string(),
 
 
104
  };
105
  let status_json = serde_json::to_string(&status).unwrap();
106
- let _: () = sched.client().set(format!("task:status:{}", task_id), status_json, Some(fred::types::Expiration::EX(86400)), None, false).await.unwrap_or_default();
 
 
 
 
 
 
 
 
 
 
107
  }
108
  storage.upload_hls_dir(&output_dir, &s3_prefix).await?;
109
-
110
  // Upload thumbnail too
111
  if !skip_thumbnail {
112
  let thumb_path = format!("{}.jpg", video_path);
113
  let thumb_key = format!("thumbnails/{}.jpg", task_id);
114
  storage.upload_file(Path::new(&thumb_path), &thumb_key).await?;
115
  }
116
- },
117
  Err(e) => {
118
  eprintln!("Storage Manager initialization failed: {}. Skipping upload.", e);
 
 
 
119
  return Err(anyhow!("Storage initialization failed: {}", e));
120
  }
121
  }
122
  Ok(())
123
  }
124
 
125
- async fn get_video_metadata(video_path: &str) -> Result<(i32, i32, bool)> {
 
 
 
126
  let output = Command::new("ffprobe")
127
  .args(&[
128
- "-v", "error", "-select_streams", "v:0",
129
- "-show_entries", "stream=width,height",
130
- "-of", "csv=s=x:p=0",
 
 
 
 
 
131
  video_path,
132
  ])
133
- .output().await?;
134
-
 
135
  let s = String::from_utf8(output.stdout)?;
136
  let parts: Vec<&str> = s.trim().split('x').collect();
137
  if parts.len() != 2 {
@@ -144,27 +273,84 @@ async fn get_video_metadata(video_path: &str) -> Result<(i32, i32, bool)> {
144
  // Check for audio
145
  let audio_output = Command::new("ffprobe")
146
  .args(&[
147
- "-v", "error", "-select_streams", "a",
148
- "-show_entries", "stream=index",
149
- "-of", "csv=p=0",
 
 
 
 
 
150
  video_path,
151
  ])
152
- .output().await?;
153
-
 
154
  let has_audio = !String::from_utf8(audio_output.stdout)?.trim().is_empty();
155
 
156
- Ok((width, height, has_audio))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  }
158
 
159
  async fn transcode_tiered(
160
- input: &str,
161
- output_dir: &str,
162
- format: &str,
163
  config: &TranscodingConfig,
164
  scheduler: Option<WeightedScheduler>,
165
  task_id: String,
166
  has_audio: bool,
167
- tier: &UserTier
 
168
  ) -> Result<()> {
169
  println!("Transcoding tiered levels for {} -> {}", input, output_dir);
170
 
@@ -177,58 +363,85 @@ async fn transcode_tiered(
177
  // root cause of FFmpeg error "Same elementary stream found more than once".
178
  let (filter, stream_map, num_variants): (String, String, usize) = if format == "flash" {
179
  // Single quality for flash (Original resolution)
180
- let sm = if has_audio { "v:0,a:0,name:original".to_string() } else { "v:0,name:original".to_string() };
 
 
 
 
181
  (format!("[0:v]scale=w=-2:h={}[vout]", source_height), sm, 1)
182
  } else if config.max_height <= 720 {
183
  // Free tier β€” two quality levels, capped at 720p
184
  let sm = if has_audio {
185
- "v:0,a:0,name:720p v:1,a:1,name:480p".to_string() // ← unique a:0 / a:1
186
  } else {
187
  "v:0,name:720p v:1,name:480p".to_string()
188
  };
189
  (
190
  "[0:v]split=2[v1][v2]; [v1]scale=w=-2:h=720[v1out]; [v2]scale=w=-2:h=480[v2out]".to_string(),
191
- sm, 2
 
192
  )
193
  } else {
194
  // Pro tier β€” three quality levels up to 1080p
195
  let sm = if has_audio {
196
- "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
197
  } else {
198
  "v:0,name:1080p v:1,name:720p v:2,name:480p".to_string()
199
  };
200
  (
201
  "[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(),
202
- sm, 3
 
203
  )
204
  };
205
 
206
  // ── 2. Build args as Vec<String> so we can push dynamic per-stream options ─
207
  let mut args: Vec<String> = vec![
208
- "-i".into(), input.into(),
 
209
  // NOTE: Do NOT add global -c:a here β€” it conflicts with per-stream -c:a:N below
210
- "-preset".into(), config.preset.clone(),
211
- "-crf".into(), config.crf.clone(),
212
- "-f".into(), "hls".into(),
213
- "-hls_time".into(), "6".into(),
214
- "-hls_playlist_type".into(), "vod".into(),
215
- "-master_pl_name".into(), "master.m3u8".into(),
216
- "-filter_complex".into(), filter.clone(),
 
 
 
 
 
 
 
217
  ];
218
 
219
  // ── 3. Video stream mappings ─────────────────────────────────────────────
220
  if filter.contains("split=3") {
221
- args.extend(["-map","[v1out]","-c:v:0","libx264","-b:v:0","5000k",
222
- "-map","[v2out]","-c:v:1","libx264","-b:v:1","2800k",
223
- "-map","[v3out]","-c:v:2","libx264","-b:v:2","1200k"]
224
- .iter().map(|s| s.to_string()));
 
 
 
 
 
225
  } else if filter.contains("split=2") {
226
- args.extend(["-map","[v1out]","-c:v:0","libx264","-b:v:0","2800k",
227
- "-map","[v2out]","-c:v:1","libx264","-b:v:1","1200k"]
228
- .iter().map(|s| s.to_string()));
 
 
 
 
 
229
  } else {
230
- args.extend(["-map","[vout]","-c:v:0","libx264","-b:v:0","2800k"]
231
- .iter().map(|s| s.to_string()));
 
 
 
232
  }
233
 
234
  // ── 4. Audio stream mappings ─────────────────────────────────────────────
@@ -250,11 +463,13 @@ async fn transcode_tiered(
250
 
251
  // ── 5. HLS output options ────────────────────────────────────────────────
252
  let segment_filename = format!("{}/%v_%03d.ts", output_dir);
253
- let output_pattern = format!("{}/%v.m3u8", output_dir);
254
 
255
  args.extend([
256
- "-hls_segment_filename".to_string(), segment_filename,
257
- "-var_stream_map".to_string(), stream_map,
 
 
258
  output_pattern,
259
  ]);
260
 
@@ -263,43 +478,212 @@ async fn transcode_tiered(
263
  progress: 15,
264
  status: "processing".to_string(),
265
  message: format!("Compressing and optimizing video (Tier: {:?})", tier),
 
 
266
  };
267
  let status_json = serde_json::to_string(&status).unwrap();
268
- let _: () = sched.client().set(format!("task:status:{}", task_id), status_json, Some(fred::types::Expiration::EX(86400)), None, false).await.unwrap_or_default();
 
 
 
 
 
 
 
 
 
 
 
269
  }
270
 
271
- let output = Command::new("ffmpeg").args(&args).output().await?;
272
- if !output.status.success() {
273
- let err = String::from_utf8_lossy(&output.stderr);
274
- eprintln!("FFmpeg Error: {}", err);
275
- return Err(anyhow!("FFmpeg failed: {}", err));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  }
277
- Ok(())
278
 
 
 
 
 
279
  }
280
 
281
  async fn get_video_height(input: &str) -> Result<i32> {
282
  let output = Command::new("ffprobe")
283
- .args(&["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=height", "-of", "csv=p=0", input])
284
- .output().await?;
 
 
 
 
 
 
 
 
 
 
 
285
  let s = String::from_utf8(output.stdout)?;
286
  Ok(s.trim().parse()?)
287
  }
288
 
289
  async fn generate_thumbnail(video_path: &str) -> Result<()> {
 
290
  let thumb_path = format!("{}.jpg", video_path);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  let status = Command::new("ffmpeg")
292
  .args(&[
293
- "-ss", "00:00:01",
294
- "-i", video_path,
295
- "-frames:v", "1",
296
- "-update", "1",
297
- "-q:v", "2",
298
- "-y", &thumb_path
 
 
 
 
 
 
299
  ])
300
- .status().await?;
 
301
  if !status.success() {
302
- return Err(anyhow!("Thumbnail generation failed"));
 
 
 
303
  }
304
  Ok(())
305
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  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;
12
 
13
+ /// Redis key TTL for live encode progress (seconds).
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,
 
38
  }
39
  }
40
 
41
+ fn job_progress_key(job_id: &str) -> String {
42
+ format!("job:progress:{}", job_id)
43
+ }
44
+
45
+ /// Write live encode progress `0..=100` to `job:progress:{job_id}` (fred Redis client).
46
+ pub async fn set_job_progress(sched: &WeightedScheduler, job_id: &str, percent: u32) {
47
+ let pct = percent.min(100);
48
+ let _: () = sched
49
+ .client()
50
+ .set(
51
+ job_progress_key(job_id),
52
+ pct.to_string(),
53
+ Some(fred::types::Expiration::EX(JOB_PROGRESS_TTL_SECS)),
54
+ None,
55
+ false,
56
+ )
57
+ .await
58
+ .unwrap_or_default();
59
+ }
60
+
61
+ /// Remove progress key so failed jobs do not leave a stale percentage.
62
+ pub async fn clear_job_progress(sched: &WeightedScheduler, job_id: &str) {
63
+ let _: () = sched
64
+ .client()
65
+ .del(job_progress_key(job_id))
66
+ .await
67
+ .unwrap_or_default();
68
+ }
69
+
70
  pub async fn process(
71
  _video_id: String, // Platform ID
72
  video_path: &str, // Local filesystem path
73
+ format: &str,
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() {
83
  return Err(anyhow!("Video file not found at path: {}", video_path));
84
  }
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 {
116
+ clear_job_progress(sched, &task_id).await;
117
+ }
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 ────────────────────────────────────────────────
128
+ // Reject jobs whose declared format (home/flash) does not match actual pixel
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 {
136
+ "flash" => ratio > 1.1, // declared flash but video is landscape
137
+ "home" => ratio < 0.9, // declared home but video is portrait
138
+ _ => false,
139
+ };
140
+ if mismatch {
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,
149
+ );
150
+ eprintln!("{}", msg);
151
+ if let Some(ref sched) = scheduler {
152
+ clear_job_progress(sched, &task_id).await;
153
+ }
154
+ return Err(anyhow!("{}", msg));
155
+ }
156
+ }
157
+ }
158
+
159
  // 2. Prep Output
160
  let output_dir = format!("{}_hls", video_path);
161
  if !Path::new(&output_dir).exists() {
 
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 {
 
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 {
 
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
+ /// Probe width/height, audio presence, and total duration (seconds).
246
+ /// Duration comes from format context (`format=duration`), with stream duration as fallback β€”
247
+ /// equivalent to reading container duration / stream time_baseΓ—duration in ffmpeg-next.
248
+ async fn get_video_metadata(video_path: &str) -> Result<(i32, i32, bool, f64)> {
249
  let output = Command::new("ffprobe")
250
  .args(&[
251
+ "-v",
252
+ "error",
253
+ "-select_streams",
254
+ "v:0",
255
+ "-show_entries",
256
+ "stream=width,height",
257
+ "-of",
258
+ "csv=s=x:p=0",
259
  video_path,
260
  ])
261
+ .output()
262
+ .await?;
263
+
264
  let s = String::from_utf8(output.stdout)?;
265
  let parts: Vec<&str> = s.trim().split('x').collect();
266
  if parts.len() != 2 {
 
273
  // Check for audio
274
  let audio_output = Command::new("ffprobe")
275
  .args(&[
276
+ "-v",
277
+ "error",
278
+ "-select_streams",
279
+ "a",
280
+ "-show_entries",
281
+ "stream=index",
282
+ "-of",
283
+ "csv=p=0",
284
  video_path,
285
  ])
286
+ .output()
287
+ .await?;
288
+
289
  let has_audio = !String::from_utf8(audio_output.stdout)?.trim().is_empty();
290
 
291
+ let duration_secs = get_video_duration_secs(video_path).await.unwrap_or(0.0);
292
+
293
+ Ok((width, height, has_audio, duration_secs))
294
+ }
295
+
296
+ async fn get_video_duration_secs(video_path: &str) -> Result<f64> {
297
+ // Prefer container / format duration (same source as AVFormatContext.duration).
298
+ let format_out = Command::new("ffprobe")
299
+ .args(&[
300
+ "-v",
301
+ "error",
302
+ "-show_entries",
303
+ "format=duration",
304
+ "-of",
305
+ "default=noprint_wrappers=1:nokey=1",
306
+ video_path,
307
+ ])
308
+ .output()
309
+ .await?;
310
+
311
+ let format_s = String::from_utf8_lossy(&format_out.stdout).trim().to_string();
312
+ if let Ok(d) = format_s.parse::<f64>() {
313
+ if d.is_finite() && d > 0.0 {
314
+ return Ok(d);
315
+ }
316
+ }
317
+
318
+ // Fallback: stream duration (seconds) β€” akin to stream.duration * av_q2d(time_base).
319
+ let stream_out = Command::new("ffprobe")
320
+ .args(&[
321
+ "-v",
322
+ "error",
323
+ "-select_streams",
324
+ "v:0",
325
+ "-show_entries",
326
+ "stream=duration",
327
+ "-of",
328
+ "default=noprint_wrappers=1:nokey=1",
329
+ video_path,
330
+ ])
331
+ .output()
332
+ .await?;
333
+
334
+ let stream_s = String::from_utf8_lossy(&stream_out.stdout).trim().to_string();
335
+ let d: f64 = stream_s
336
+ .parse()
337
+ .map_err(|_| anyhow!("Invalid duration from ffprobe: format={:?} stream={:?}", format_s, stream_s))?;
338
+ if !d.is_finite() || d <= 0.0 {
339
+ return Err(anyhow!("Non-positive duration: {}", d));
340
+ }
341
+ Ok(d)
342
  }
343
 
344
  async fn transcode_tiered(
345
+ input: &str,
346
+ output_dir: &str,
347
+ format: &str,
348
  config: &TranscodingConfig,
349
  scheduler: Option<WeightedScheduler>,
350
  task_id: String,
351
  has_audio: bool,
352
+ tier: &UserTier,
353
+ duration_secs: f64,
354
  ) -> Result<()> {
355
  println!("Transcoding tiered levels for {} -> {}", input, output_dir);
356
 
 
363
  // root cause of FFmpeg error "Same elementary stream found more than once".
364
  let (filter, stream_map, num_variants): (String, String, usize) = if format == "flash" {
365
  // Single quality for flash (Original resolution)
366
+ let sm = if has_audio {
367
+ "v:0,a:0,name:original".to_string()
368
+ } else {
369
+ "v:0,name:original".to_string()
370
+ };
371
  (format!("[0:v]scale=w=-2:h={}[vout]", source_height), sm, 1)
372
  } else if config.max_height <= 720 {
373
  // Free tier β€” two quality levels, capped at 720p
374
  let sm = if has_audio {
375
+ "v:0,a:0,name:720p v:1,a:1,name:480p".to_string() // ← unique a:0 / a:1
376
  } else {
377
  "v:0,name:720p v:1,name:480p".to_string()
378
  };
379
  (
380
  "[0:v]split=2[v1][v2]; [v1]scale=w=-2:h=720[v1out]; [v2]scale=w=-2:h=480[v2out]".to_string(),
381
+ sm,
382
+ 2,
383
  )
384
  } else {
385
  // Pro tier β€” three quality levels up to 1080p
386
  let sm = if has_audio {
387
+ "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
388
  } else {
389
  "v:0,name:1080p v:1,name:720p v:2,name:480p".to_string()
390
  };
391
  (
392
  "[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(),
393
+ sm,
394
+ 3,
395
  )
396
  };
397
 
398
  // ── 2. Build args as Vec<String> so we can push dynamic per-stream options ─
399
  let mut args: Vec<String> = vec![
400
+ "-i".into(),
401
+ input.into(),
402
  // NOTE: Do NOT add global -c:a here β€” it conflicts with per-stream -c:a:N below
403
+ "-preset".into(),
404
+ config.preset.clone(),
405
+ "-crf".into(),
406
+ config.crf.clone(),
407
+ "-f".into(),
408
+ "hls".into(),
409
+ "-hls_time".into(),
410
+ "6".into(),
411
+ "-hls_playlist_type".into(),
412
+ "vod".into(),
413
+ "-master_pl_name".into(),
414
+ "master.m3u8".into(),
415
+ "-filter_complex".into(),
416
+ filter.clone(),
417
  ];
418
 
419
  // ── 3. Video stream mappings ─────────────────────────────────────────────
420
  if filter.contains("split=3") {
421
+ args.extend(
422
+ [
423
+ "-map", "[v1out]", "-c:v:0", "libx264", "-b:v:0", "5000k", "-map", "[v2out]",
424
+ "-c:v:1", "libx264", "-b:v:1", "2800k", "-map", "[v3out]", "-c:v:2", "libx264",
425
+ "-b:v:2", "1200k",
426
+ ]
427
+ .iter()
428
+ .map(|s| s.to_string()),
429
+ );
430
  } else if filter.contains("split=2") {
431
+ args.extend(
432
+ [
433
+ "-map", "[v1out]", "-c:v:0", "libx264", "-b:v:0", "2800k", "-map", "[v2out]",
434
+ "-c:v:1", "libx264", "-b:v:1", "1200k",
435
+ ]
436
+ .iter()
437
+ .map(|s| s.to_string()),
438
+ );
439
  } else {
440
+ args.extend(
441
+ ["-map", "[vout]", "-c:v:0", "libx264", "-b:v:0", "2800k"]
442
+ .iter()
443
+ .map(|s| s.to_string()),
444
+ );
445
  }
446
 
447
  // ── 4. Audio stream mappings ─────────────────────────────────────────────
 
463
 
464
  // ── 5. HLS output options ────────────────────────────────────────────────
465
  let segment_filename = format!("{}/%v_%03d.ts", output_dir);
466
+ let output_pattern = format!("{}/%v.m3u8", output_dir);
467
 
468
  args.extend([
469
+ "-hls_segment_filename".to_string(),
470
+ segment_filename,
471
+ "-var_stream_map".to_string(),
472
+ stream_map,
473
  output_pattern,
474
  ]);
475
 
 
478
  progress: 15,
479
  status: "processing".to_string(),
480
  message: format!("Compressing and optimizing video (Tier: {:?})", tier),
481
+ cover_url: None,
482
+ cover_source: None,
483
  };
484
  let status_json = serde_json::to_string(&status).unwrap();
485
+ let _: () = sched
486
+ .client()
487
+ .set(
488
+ format!("task:status:{}", task_id),
489
+ status_json,
490
+ Some(fred::types::Expiration::EX(86400)),
491
+ None,
492
+ false,
493
+ )
494
+ .await
495
+ .unwrap_or_default();
496
+ set_job_progress(sched, &task_id, 0).await;
497
  }
498
 
499
+ run_ffmpeg_with_progress(&args, duration_secs, scheduler.as_ref(), &task_id).await
500
+ }
501
+
502
+ /// Spawn ffmpeg with `-progress pipe:1`, map `out_time` β†’ percent of input duration,
503
+ /// and throttle Redis writes to ~1/sec on `job:progress:{job_id}`.
504
+ ///
505
+ /// This is the CLI equivalent of walking PTS in an ffmpeg-next encode loop:
506
+ /// `progress = (pts * time_base / total_duration) * 100`.
507
+ async fn run_ffmpeg_with_progress(
508
+ args: &[String],
509
+ duration_secs: f64,
510
+ scheduler: Option<&WeightedScheduler>,
511
+ task_id: &str,
512
+ ) -> Result<()> {
513
+ // Machine-readable progress on stdout; keep stderr for errors (drained so the pipe never blocks).
514
+ let mut full_args: Vec<String> = vec![
515
+ "-nostats".into(),
516
+ "-progress".into(),
517
+ "pipe:1".into(),
518
+ ];
519
+ full_args.extend(args.iter().cloned());
520
+
521
+ let mut child = Command::new("ffmpeg")
522
+ .args(&full_args)
523
+ .stdout(Stdio::piped())
524
+ .stderr(Stdio::piped())
525
+ .spawn()?;
526
+
527
+ let stdout = child
528
+ .stdout
529
+ .take()
530
+ .ok_or_else(|| anyhow!("ffmpeg stdout not captured"))?;
531
+ let stderr = child
532
+ .stderr
533
+ .take()
534
+ .ok_or_else(|| anyhow!("ffmpeg stderr not captured"))?;
535
+
536
+ let stderr_task = tokio::spawn(async move {
537
+ let mut buf = Vec::new();
538
+ let mut reader = BufReader::new(stderr);
539
+ let _ = reader.read_to_end(&mut buf).await;
540
+ String::from_utf8_lossy(&buf).to_string()
541
+ });
542
+
543
+ let mut lines = BufReader::new(stdout).lines();
544
+ let mut last_report = Instant::now()
545
+ .checked_sub(PROGRESS_REPORT_INTERVAL)
546
+ .unwrap_or_else(Instant::now);
547
+ let mut current_out_us: u64 = 0;
548
+
549
+ while let Some(line) = lines.next_line().await? {
550
+ let line = line.trim();
551
+ if let Some(v) = line.strip_prefix("out_time_us=") {
552
+ if let Ok(us) = v.parse::<u64>() {
553
+ current_out_us = us;
554
+ }
555
+ } else if let Some(v) = line.strip_prefix("out_time_ms=") {
556
+ // Historical ffmpeg key: value is microseconds despite the name.
557
+ if let Ok(us) = v.parse::<u64>() {
558
+ current_out_us = us;
559
+ }
560
+ } else if line.starts_with("progress=") {
561
+ let force = line == "progress=end";
562
+ if force || last_report.elapsed() >= PROGRESS_REPORT_INTERVAL {
563
+ if duration_secs > 0.0 {
564
+ let current_time_seconds = current_out_us as f64 / 1_000_000.0;
565
+ // Cap at 99 until process exit confirms success (then we set 100).
566
+ let progress_percent =
567
+ ((current_time_seconds / duration_secs) * 100.0).clamp(0.0, 99.0) as u32;
568
+ if let Some(sched) = scheduler {
569
+ set_job_progress(sched, task_id, progress_percent).await;
570
+ }
571
+ }
572
+ last_report = Instant::now();
573
+ }
574
+ }
575
+ }
576
+
577
+ let status = child.wait().await?;
578
+ let err_text = stderr_task.await.unwrap_or_default();
579
+
580
+ if !status.success() {
581
+ eprintln!("FFmpeg Error: {}", err_text);
582
+ if let Some(sched) = scheduler {
583
+ clear_job_progress(sched, task_id).await;
584
+ }
585
+ return Err(anyhow!("FFmpeg failed: {}", err_text));
586
  }
 
587
 
588
+ if let Some(sched) = scheduler {
589
+ set_job_progress(sched, task_id, 100).await;
590
+ }
591
+ Ok(())
592
  }
593
 
594
  async fn get_video_height(input: &str) -> Result<i32> {
595
  let output = Command::new("ffprobe")
596
+ .args(&[
597
+ "-v",
598
+ "error",
599
+ "-select_streams",
600
+ "v:0",
601
+ "-show_entries",
602
+ "stream=height",
603
+ "-of",
604
+ "csv=p=0",
605
+ input,
606
+ ])
607
+ .output()
608
+ .await?;
609
  let s = String::from_utf8(output.stdout)?;
610
  Ok(s.trim().parse()?)
611
  }
612
 
613
  async fn generate_thumbnail(video_path: &str) -> Result<()> {
614
+ // Legacy path (thumbnails next to source). Prefer generate_and_upload_auto_cover.
615
  let thumb_path = format!("{}.jpg", video_path);
616
+ extract_cover_frame(video_path, &thumb_path, 0.1).await
617
+ }
618
+
619
+ /// Seek ~`pct` into the video (default 10%) and write a single JPEG frame.
620
+ /// Uses the system ffmpeg CLI (same stack as the rest of this service; equivalent
621
+ /// to grabbing a decoded frame via ffmpeg-next around that timestamp).
622
+ pub async fn extract_cover_frame(video_path: &str, out_jpg: &str, pct: f64) -> Result<()> {
623
+ let duration = match get_video_metadata(video_path).await {
624
+ Ok((_, _, _, d)) if d.is_finite() && d > 0.0 => d,
625
+ _ => 0.0,
626
+ };
627
+ let seek_secs = if duration > 0.5 {
628
+ (duration * pct).clamp(0.0, (duration - 0.05).max(0.0))
629
+ } else {
630
+ 0.0
631
+ };
632
+ let seek_arg = format!("{:.3}", seek_secs);
633
+
634
+ println!(
635
+ "Extracting cover frame from {} at {}s ({:.0}% of {:.2}s) β†’ {}",
636
+ video_path,
637
+ seek_arg,
638
+ pct * 100.0,
639
+ duration,
640
+ out_jpg
641
+ );
642
+
643
  let status = Command::new("ffmpeg")
644
  .args(&[
645
+ "-ss",
646
+ &seek_arg,
647
+ "-i",
648
+ video_path,
649
+ "-frames:v",
650
+ "1",
651
+ "-update",
652
+ "1",
653
+ "-q:v",
654
+ "2",
655
+ "-y",
656
+ out_jpg,
657
  ])
658
+ .status()
659
+ .await?;
660
  if !status.success() {
661
+ return Err(anyhow!("Cover frame extraction failed"));
662
+ }
663
+ if !Path::new(out_jpg).exists() {
664
+ return Err(anyhow!("Cover JPEG was not written: {}", out_jpg));
665
  }
666
  Ok(())
667
  }
668
+
669
+ /// Auto cover: frame at ~10% duration β†’ JPEG β†’ S3 `covers/{task_id}.jpg`.
670
+ /// Returns the S3 key for inclusion in the Redis completion payload.
671
+ pub async fn generate_and_upload_auto_cover(
672
+ video_path: &str,
673
+ task_id: &str,
674
+ storage: &StorageManager,
675
+ ) -> Result<String> {
676
+ let cover_local = format!("{}_cover.jpg", video_path);
677
+ extract_cover_frame(video_path, &cover_local, 0.1).await?;
678
+
679
+ let cover_key = format!("covers/{}.jpg", task_id);
680
+ storage
681
+ .upload_file(Path::new(&cover_local), &cover_key)
682
+ .await?;
683
+
684
+ // Best-effort cleanup of local JPEG
685
+ let _ = fs::remove_file(&cover_local).await;
686
+
687
+ println!("Auto cover uploaded: {}", cover_key);
688
+ Ok(cover_key)
689
+ }
src/worker.rs CHANGED
@@ -4,7 +4,8 @@ use sysinfo::{System, SystemExt};
4
  use crate::queue::WeightedScheduler;
5
  use fred::interfaces::KeysInterface;
6
  use crate::transcoder;
7
- use crate::models::TaskStatus;
 
8
 
9
  pub struct WorkerPool {
10
  scheduler: WeightedScheduler,
@@ -15,7 +16,7 @@ impl WorkerPool {
15
  pub fn new(scheduler: WeightedScheduler) -> Self {
16
  let max_procs = calculate_max_processes();
17
  println!("Initializing Worker Pool with {} slots", max_procs);
18
-
19
  Self {
20
  scheduler,
21
  semaphore: Arc::new(Semaphore::new(max_procs)),
@@ -24,98 +25,21 @@ impl WorkerPool {
24
 
25
  pub async fn start(&self) {
26
  println!("Worker Pool started. Polling for tasks...");
27
-
28
  loop {
29
  // Wait for a slot to be available before even pulling a task
30
  // This prevents filling RAM with tasks that are just waiting
31
  let permit = self.semaphore.clone().acquire_owned().await.unwrap();
32
-
33
  match self.scheduler.next_task().await {
34
  Ok(task) => {
35
  let scheduler = self.scheduler.clone();
36
-
37
  tokio::spawn(async move {
38
  let _permit = permit; // Hold permit until done
39
- let task_id = task.task_id.clone();
40
- let s3_key = task.video_id.clone();
41
- let tier = task.tier.clone();
42
- let target_format = task.target_format.clone();
43
- let skip_thumbnail = task.skip_thumbnail;
44
-
45
- // Phase 0: Download from S3
46
- let storage = match crate::storage::StorageManager::new().await {
47
- Ok(s) => s,
48
- Err(e) => {
49
- eprintln!("Failed to initialize StorageManager for task {}: {}", task_id, e);
50
- return;
51
- }
52
- };
53
-
54
- let temp_file = match tempfile::NamedTempFile::new() {
55
- Ok(f) => f,
56
- Err(e) => {
57
- eprintln!("Failed to create temp file for task {}: {}", task_id, e);
58
- return;
59
- }
60
- };
61
- let temp_path = temp_file.path().to_str().unwrap().to_string();
62
-
63
- println!("Downloading {} from S3 to {}", s3_key, temp_path);
64
- if let Err(e) = storage.download_file(&s3_key, temp_file.path()).await {
65
- eprintln!("Download failed for task {}: {}", task_id, e);
66
- let status = TaskStatus {
67
- progress: 0,
68
- status: "error".to_string(),
69
- message: format!("Download failed: {}", e),
70
- };
71
- let status_json = serde_json::to_string(&status).unwrap();
72
- let _: () = scheduler.client().set(format!("task:status:{}", task_id), status_json, Some(fred::types::Expiration::EX(86400)), None, false).await.unwrap_or_default();
73
- return;
74
- }
75
-
76
- // Phase 1: Processing with retries
77
- for attempt in 1..=3 {
78
- if attempt > 1 { println!("Retrying {} (Attempt {})", task_id, attempt); }
79
-
80
- let res = transcoder::process(
81
- task_id.clone(),
82
- &temp_path,
83
- &target_format,
84
- tier.clone(),
85
- skip_thumbnail,
86
- Some(scheduler.clone()),
87
- task_id.clone()
88
- ).await;
89
-
90
- match res {
91
- Ok(_) => {
92
- println!("Completed Task: {}", task_id);
93
- let status = TaskStatus {
94
- progress: 100,
95
- status: "completed".to_string(),
96
- message: "Video live and distributed globally!".to_string(),
97
- };
98
- let status_json = serde_json::to_string(&status).unwrap();
99
- let _: () = scheduler.client().set(format!("task:status:{}", task_id), status_json, Some(fred::types::Expiration::EX(86400)), None, false).await.unwrap_or_default();
100
- break;
101
- },
102
- Err(e) if attempt == 3 => {
103
- eprintln!("Failed Task {} after 3 attempts: {}", task_id, e);
104
- let status = TaskStatus {
105
- progress: 0,
106
- status: "error".to_string(),
107
- message: format!("Final error: {}", e),
108
- };
109
- let status_json = serde_json::to_string(&status).unwrap();
110
- let _: () = scheduler.client().set(format!("task:status:{}", task_id), status_json, Some(fred::types::Expiration::EX(86400)), None, false).await.unwrap_or_default();
111
- },
112
- Err(_) => {
113
- tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
114
- }
115
- }
116
- }
117
  });
118
- },
119
  Err(_) => {
120
  // No tasks or wait timeout
121
  tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
@@ -125,13 +49,190 @@ impl WorkerPool {
125
  }
126
  }
127
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  fn calculate_max_processes() -> usize {
129
  let mut sys = System::new_all();
130
  sys.refresh_all();
131
 
132
  let cpus = sys.cpus().len();
133
  let total_ram_gb = sys.total_memory() as f64 / (1024.0 * 1024.0 * 1024.0);
134
-
135
  // Formula: min(cpus/2, ram/1.5, disk_limit)
136
  let cpu_limit = (cpus as f64 / 2.0).floor() as usize;
137
  let ram_limit = (total_ram_gb / 1.5).floor() as usize;
@@ -141,7 +242,7 @@ fn calculate_max_processes() -> usize {
141
  .unwrap_or(4);
142
 
143
  let calculated = cpu_limit.min(ram_limit).min(disk_limit);
144
-
145
  // Ensure at least 1 worker
146
  calculated.max(1)
147
  }
 
4
  use crate::queue::WeightedScheduler;
5
  use fred::interfaces::KeysInterface;
6
  use crate::transcoder;
7
+ use crate::models::{TaskStatus, VideoTask};
8
+ use crate::storage::StorageManager;
9
 
10
  pub struct WorkerPool {
11
  scheduler: WeightedScheduler,
 
16
  pub fn new(scheduler: WeightedScheduler) -> Self {
17
  let max_procs = calculate_max_processes();
18
  println!("Initializing Worker Pool with {} slots", max_procs);
19
+
20
  Self {
21
  scheduler,
22
  semaphore: Arc::new(Semaphore::new(max_procs)),
 
25
 
26
  pub async fn start(&self) {
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 {
35
  Ok(task) => {
36
  let scheduler = self.scheduler.clone();
37
+
38
  tokio::spawn(async move {
39
  let _permit = permit; // Hold permit until done
40
+ process_video_job(scheduler, task).await;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  });
42
+ }
43
  Err(_) => {
44
  // No tasks or wait timeout
45
  tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
 
49
  }
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();
57
+ let tier = task.tier.clone();
58
+ let target_format = task.target_format.clone();
59
+
60
+ // 1) cover_source from payload β€” missing/empty β‡’ "auto" (backward compatible)
61
+ let cover_source = {
62
+ let raw = task.cover_source.trim().to_lowercase();
63
+ if raw.is_empty() {
64
+ "auto".to_string()
65
+ } else {
66
+ raw
67
+ }
68
+ };
69
+ let cover_s3_key = task.cover_s3_key.clone();
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
+ };
79
+
80
+ let temp_file = match tempfile::NamedTempFile::new() {
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 {
109
+ if attempt > 1 {
110
+ println!("Retrying {} (Attempt {})", task_id, attempt);
111
+ }
112
+
113
+ let res = transcoder::process(
114
+ task_id.clone(),
115
+ &temp_path,
116
+ &target_format,
117
+ tier.clone(),
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(|| {
136
+ format!("covers/{}.jpg", task_id)
137
+ });
138
+ println!("Using custom cover (skip generation): {}", key);
139
+ key
140
+ } else {
141
+ // Auto (or missing): extract ~10% frame, JPEG, upload covers/{task_id}.jpg
142
+ match transcoder::generate_and_upload_auto_cover(
143
+ &temp_path,
144
+ &task_id,
145
+ &storage,
146
+ )
147
+ .await
148
+ {
149
+ Ok(key) => key,
150
+ Err(e) => {
151
+ eprintln!(
152
+ "Auto cover generation failed for {}: {} β€” marking error",
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;
169
+ }
170
+ }
171
+ };
172
+
173
+ // 4) Completion payload for Celery /status consumers
174
+ write_task_status(
175
+ &scheduler,
176
+ &task_id,
177
+ TaskStatus {
178
+ progress: 100,
179
+ status: "completed".to_string(),
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;
186
+ break;
187
+ }
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
+ }
204
+ Err(_) => {
205
+ transcoder::clear_job_progress(&scheduler, &task_id).await;
206
+ tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
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
+ });
216
+ let _: () = scheduler
217
+ .client()
218
+ .set(
219
+ format!("task:status:{}", task_id),
220
+ status_json,
221
+ Some(fred::types::Expiration::EX(86400)),
222
+ None,
223
+ false,
224
+ )
225
+ .await
226
+ .unwrap_or_default();
227
+ }
228
+
229
  fn calculate_max_processes() -> usize {
230
  let mut sys = System::new_all();
231
  sys.refresh_all();
232
 
233
  let cpus = sys.cpus().len();
234
  let total_ram_gb = sys.total_memory() as f64 / (1024.0 * 1024.0 * 1024.0);
235
+
236
  // Formula: min(cpus/2, ram/1.5, disk_limit)
237
  let cpu_limit = (cpus as f64 / 2.0).floor() as usize;
238
  let ram_limit = (total_ram_gb / 1.5).floor() as usize;
 
242
  .unwrap_or(4);
243
 
244
  let calculated = cpu_limit.min(ram_limit).min(disk_limit);
245
+
246
  // Ensure at least 1 worker
247
  calculated.max(1)
248
  }